//
//  AppDataManager.m
//  BanBu
//
//  Created by 17xy on 12-8-3.
//
//

#import "AppDataManager.h"
#import "AppCommunicationManager.h"
#import "BanBu_SmileLabel.h"
#import "BanBu_AppDelegate.h"
#import "BanBu_ChatViewController.h"
#import "CJSONSerializer.h"
#import "NSDictionary_JSONExtensions.h"
#import <CommonCrypto/CommonDigest.h>
#import "CJSONDeserializer.h"
#import "BanBu_MyFriendViewController.h"
#import "BanBu_ChatCellAPI.h"
#import "BanBu_DialogueController.h"
#import "BanBu_FriendListController.h"
#import "BanBu_TransmitViewController.h"
#import "BanBu_SmileView.h"
#import "BanBu_SecondaryDialogueViewController.h"
#import "LeveyTabBarController.h"
#import "BanBu_NoDisturbingViewController.h"
#import "CustomStatueBar.h"
#import "BanBu_SpecialText.h"
#import "BanBu_SendMsg.h"
#import "LeveyTabBarController.h"
#import "BanBu_HintsViewCell.h"
#import "BanBu_EmoStoreViewController.h"
#import "BanBu_ChatBackgroundSettingViewController.h"
#import "BanBu_BubbleViewController.h"

#define DataBasePath  [DataCachePath stringByAppendingPathComponent:@"data.db"]
@interface AppDataManager()

-(void)createMusic;
@end

@implementation AppDataManager

@synthesize regDic = _regDic;
@synthesize loginid = _loginid;
@synthesize nearBuddys=_nearBuddys;
@synthesize nearDos = _nearDos;
@synthesize zibarString = _zibarString;
@synthesize deep=_deep;
@synthesize LanguageDateString=_LanguageDateString;
@synthesize dateString=_dateString;
@synthesize blackString=_blackString;
@synthesize languageDictionary=_languageDictionary;
@synthesize Messagetype=_Messagetype;
@synthesize unLoginArr=_unLoginArr;
@synthesize emiNameArr=_emiNameArr;
@synthesize emiLanguageArr=_emiLanguageArr;
@synthesize isSee=_isSee;
@synthesize agreeList=_agreeList;
@synthesize time=_time;
@synthesize talkArr=_talkArr;
@synthesize isPlay=_isPlay;
@synthesize playert=_playert;
@synthesize boolArr=_boolArr;
@synthesize appVersion = _appVersion;
static AppDataManager *sharedAppDataManager = nil;


- (void)dealloc
{
    self.dataBase = nil;
    self.cellRowMapDic = nil;
    self.banbuHostIP = nil;
    // 滞空 让object 即使在此release 也不崩溃
    [_useruid release],_useruid=nil;
    [_appVersion release];
    _appVersion = nil;
    [_userAvatar release],_userAvatar=nil;
    [_loginid release],_loginid=nil;
    [_chatuid release],_chatuid=nil;
    [_regDic release],_regDic=nil;
    [_nearBuddys release];
    [_nearDos release];
    [_contentArr release];
    [_friends release];
    [_friendsDos release];
    [_friendDos release];
    [_dialogs release];
    [_talkPeoples release];
    [_languageDictionary release];
    [_unReadBroadInfor release],_unReadBroadInfor = nil;
    [_messageRadioDictionary release],_messageRadioDictionary=nil;
    
    [_keyArr release],_keyArr=nil;
    [_valueArr release],_valueArr=nil;
    [_unLoginArr release],_unLoginArr=nil;
    [_emiLanguageArr release],_emiLanguageArr=nil;
    [_emiNameArr release],_emiNameArr=nil;
    [_agreeList release],_agreeList=nil;
    [_talkArr release],_talkArr=nil;
    [_boolArr release],_boolArr=nil;
    [_userDialogsDic release],_userDialogsDic = nil;
    [_readedUserArray release],_readedUserArray = nil;
    [_bubbleNameDic release],_bubbleNameDic = nil;
    [_serverTime release];
    [_smileViewBackup release];
    [_emoKeyboard release],_emoKeyboard = nil;
    [_secondaryTalkPeople release];
    [_lastSayHiUserInfoDic release];
    [super dealloc];
}


-(NSString *)theRevisedName:(NSString*)oldname andUID:(NSString *)uid{
    NSString *output = [NSString string];
    
    if(!MyAppDataManager.useruid.length)
    {
        return oldname;
    }

    NSMutableDictionary *uidDic = [NSMutableDictionary dictionaryWithDictionary:[UserDefaults valueForKey:MyAppDataManager.useruid]];
    NSArray *renameArr = [NSArray arrayWithArray:[uidDic valueForKey:@"renameflist"]];
    for(NSDictionary *renameDic in renameArr)
    {
        if([[renameDic valueForKey:@"friendid"] isEqualToString:uid])
        {
            output = [renameDic valueForKey:@"fname"];
            break;
        }
    }
    return ![output isEqualToString:@""]?output:oldname;
}

//来消息时播放声音
-(void)createMusic
{
    if (self.recordingVideo)//正在录制视频时不发出声音提示
    {
        return;
    }
    
    if(![[[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"settings"] valueForKey:@"MusicSwith"] length])
    {
        return;
    }
    else
    {
        MyAppDataManager.musicName = [[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"settings"] valueForKey:@"MusicSwith"];
    }
    NSString *path=[[NSBundle mainBundle]pathForResource:_musicName ofType:@"mp3"];
    
    if(_playert)
    {
        return;
    }
    NSError *musicError;
    
    _playert=[[AVAudioPlayer alloc]initWithData:[NSData dataWithContentsOfFile:path] error:&musicError];
    _playert.delegate = MyAppDataManager;
    
    [_playert prepareToPlay];
    _playert.volume=1.0;
    [_playert play];
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [_playert release],_playert = nil;
}

-(NSString *)IsMinGanWord:(NSString *)input
{
    if(!input)
    {
        return nil;
    }
    
    NSMutableString *change=[[[NSMutableString alloc]initWithString:input] autorelease];
    
    NSArray *stringArr=[MyAppDataManager.blackString componentsSeparatedByString:@","];
    
    for(int k=0;k<[stringArr count];k++)
    {
        NSRange range=[input rangeOfString:[stringArr objectAtIndex:k]];
        
        if(range.length==0)
        {
            continue;
        }
        else
        {
            NSMutableString *string=[[[NSMutableString alloc]init] autorelease];
            
            for(int i=0;i<range.length;i++)
            {
                [string appendString:@"*"];
            }
            
            [change replaceCharactersInRange:range withString:string];
            
            input=[NSString stringWithString:change];
            
            k=0;
        }
    }
    NSString *output=[NSString stringWithString:change];
    return output;
}

//检查是否是彩蛋，YES：是彩蛋，并且能播放；NO：不是彩蛋或是彩蛋但不能播放
-(NSArray *)easteregg:(NSString *)text
{
    NSString * filePath = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"]stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"PaintedEggshellFolder"];
    NSDictionary * eggDic = [NSDictionary dictionaryWithContentsOfFile:[filePath stringByAppendingPathComponent:@"eggs.plist"]];
    
    if (eggDic == nil)
    {
        return nil;
    }
    
    //校验是否用开启彩蛋，检查发送中的文本是否包含彩蛋关键词
    for (NSString * keyword in eggDic.allKeys)
    {
        NSArray * keyWordArr = [keyword componentsSeparatedByString:@","];
        for (NSString * keyWordStr in keyWordArr)
        {
            //检查关键字，看是不是彩蛋
            if ([text rangeOfString:keyWordStr].location != NSNotFound)
            {
                //获取彩蛋图片和语音
                NSString * imageName = [[eggDic valueForKey:keyword] valueForKey:@"imageName"];
                NSString * musicName = [[eggDic valueForKey:keyword] valueForKey:@"musicName"];
                
                NSString * imagePath = [filePath stringByAppendingPathComponent:imageName];
                NSString * musicPath = [filePath stringByAppendingPathComponent:musicName];
                
                BOOL blImagePath = [FileManager fileExistsAtPath:imagePath];
                BOOL blMusicPath = [FileManager fileExistsAtPath:musicPath];
                
                BOOL bl =(blImagePath & blMusicPath);
                
                //返回bool值，
                return @[[NSNumber numberWithBool:bl],imagePath,musicPath];
            }
        }
    }
    
    return nil;
}


//国际语言
-(NSString *)IsInternationalLanguage:(NSString *)input
{
    if(!input)
    {
        return nil;
    }
    NSMutableDictionary *languageDictionary=[[MyAppDataManager.languageDictionary objectForKey:@"language"] objectForKey:[self getLanguageSubmitToServer]];
    
    NSArray *keyArr=[languageDictionary allKeys];
    for(int i=0;i<[keyArr count];i++)
    {
        NSString *key=[keyArr objectAtIndex:i];
        
        NSRange range=[input rangeOfString:key];
        
        if(range.length==0)
            continue;
        NSString *value=[languageDictionary valueForKey:[keyArr objectAtIndex:i]];
        input=[input stringByReplacingOccurrencesOfString:key withString:value];
    }
    NSString *outstring=[NSString stringWithString:input];
    
    return outstring;
}

-(NSString*)getPreferredLanguage
{
    NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
    NSArray* languages = [defs objectForKey:@"AppleLanguages"];
    NSString* preferredLang = [languages objectAtIndex:0];
    return preferredLang;
}
//获取当前语言翻译成需要提交到谷歌的语言参数
-(NSString *)getLanguageSubmitToGoogle
{
    NSString *langauage=[MyAppDataManager getPreferredLanguage];
    if([langauage isEqual:@"zh-Hans"]){
        return @"zh-CN";
    }else if([langauage isEqual:@"ja"]){
        return @"ja";
    }
    else if([langauage isEqual:@"ko"])
    {
        return @"ko";
    }
    else if([langauage isEqual:@"zh-Hant"])
    {
        return @"zh-CN";
    }
    else if([langauage isEqual:@"ru"])
    {
        return @"ru";
    }
    else if([langauage isEqual:@"fr"])
    {
        return @"fr";
    }
    else if([langauage isEqual:@"es"])
    {
        return @"es";
    }
    else if([langauage isEqual:@"th"])
    {
        return @"th";
    }
    else if([langauage isEqual:@"de"])
    {
        return @"de";
    }
    
    else if([langauage isEqual:@"tr"])
    {
        return @"tr";
    }
    else if([langauage isEqual:@"it"])
    {
        return @"it";
    }
    else if([langauage isEqual:@"vi"])
    {
        return @"vi";
    }
    else if([langauage isEqual:@"cs"])
    {
        return @"cs";
    }
    else if([langauage isEqual:@"ms"])
    {
        return @"ml";
    }
    else if([langauage isEqual:@"id"])
    {
        return @"id";
    }
    else if([langauage isEqual:@"pt"])
    {
        return @"pt";
    }
    else if([langauage isEqual:@"ro"])
    {
        return @"ro";
    }
    else if([langauage isEqual:@"fi"])
    {
        return @"fi";
    }
    else if([langauage isEqual:@"sv"])
    {
        return @"sv";
    }
    else if([langauage isEqual:@"pl"])
    {
        return @"pl";
    }
    else if([langauage isEqual:@"uk"])
    {
        return @"uk";
    }
    else if([langauage isEqual:@"hu"])
    {
        return @"hu";
    }
    else if([langauage isEqual:@"da"])
    {
        return @"da";
    }
    else if([langauage isEqual:@"el"])
    {
        return @"el";
    }
    else if([langauage isEqual:@"nl"])
    {
        return @"nl";
    }
    else
    {
        return @"en";
    }
}
//获取当前语言翻译成需要提交到服务器的语言
-(NSString *)getLanguageSubmitToServer
{
    NSString *langauage=[MyAppDataManager getPreferredLanguage];
    if([langauage isEqual:@"zh-Hans"]){
        return @"cn";
    }else if([langauage isEqual:@"ja"]){
        return @"jp";
    }
    else if([langauage isEqual:@"ko"])
    {
        return @"kr";
    }
    else if([langauage isEqual:@"zh-Hant"])
    {
        return @"hk";
    }
    else if([langauage isEqual:@"ru"])
    {
        return @"ru";
    }
    else if([langauage isEqual:@"fr"])
    {
        return @"fr";
    }
    else if([langauage isEqual:@"es"])
    {
        return @"es";
    }
    else if([langauage isEqual:@"th"])
    {
        return @"th";
    }
    else if([langauage isEqual:@"de"])
    {
        return @"de";
    }
    
    else if([langauage isEqual:@"tr"])
    {
        return @"tr";
    }
    else if([langauage isEqual:@"it"])
    {
        return @"it";
    }
    else if([langauage isEqual:@"vi"])
    {
        return @"vi";
    }
    else if([langauage isEqual:@"cs"])
    {
        return @"cs";
    }
    else if([langauage isEqual:@"ms"])
    {
        return @"mg";
    }
    else if([langauage isEqual:@"id"])
    {
        return @"id";
    }
    else if([langauage isEqual:@"pt"])
    {
        return @"pt";
    }
    else if([langauage isEqual:@"ro"])
    {
        return @"ro";
    }
    else if([langauage isEqual:@"fi"])
    {
        return @"fi";
    }
    else if([langauage isEqual:@"nb"])
    {
        return @"nb";
    }
    else if([langauage isEqual:@"sv"])
    {
        return @"sv";
    }
    else if([langauage isEqual:@"pl"])
    {
        return @"pl";
    }
    else if([langauage isEqual:@"uk"])
    {
        return @"uk";
    }
    else if([langauage isEqual:@"hu"])
    {
        return @"hu";
    }
    else if([langauage isEqual:@"da"])
    {
        return @"da";
    }
    else if([langauage isEqual:@"el"])
    {
        return @"el";
    }
    else if([langauage isEqual:@"nl"])
    {
        return @"nl";
    }
    else
    {
        return @"en";
    }
}

NSString *(^bindLink)(NSString *,NSString *)=^(NSString *itemName,NSString *UID)
{
    return itemName;
};

- (void)initRaysource
{
    _peopleReaded = [[NSMutableDictionary alloc] initWithCapacity:5];
    if([UserDefaults valueForKey:@"peopleReaded"])
    {
        [_peopleReaded addEntriesFromDictionary:[UserDefaults valueForKey:@"peopleReaded"]];
    }
//    else
//    {
//        _peopleReaded = [[NSMutableDictionary alloc] initWithCapacity:5];
//    }
    _locationServicesEnabled = NO;
    _banbuHostIP = [[NSMutableString alloc]init];
    
    //获取上一次缓存的服务器地址07/30
    if ([UserDefaults valueForKey:lastHostIP])
    {
        [_banbuHostIP appendString:[UserDefaults valueForKey:lastHostIP]];
    }
    else
    {
        [_banbuHostIP appendString:BanBuHost];
    }
    _regDic = [[NSMutableDictionary alloc]initWithCapacity:20];
    _cellRowMapDic = [[NSMutableDictionary alloc]initWithCapacity:20];
    _nearBuddys = [[NSMutableArray alloc] initWithCapacity:10];
    _nearDos = [[NSMutableArray alloc] initWithCapacity:10];
    _contentArr = [[NSMutableArray alloc]initWithCapacity:10];
    _dialogs = [[NSMutableArray alloc] initWithCapacity:10];
    _friends = [[NSMutableArray alloc] initWithCapacity:10];
    _friendsDos = [[NSMutableArray alloc] initWithCapacity:10];
    _friendDos = [[NSMutableArray alloc] initWithCapacity:10];
    _friendViewList= [[NSMutableArray alloc] initWithCapacity:10];
    _talkPeoples = [[NSMutableArray alloc] initWithCapacity:10];
    _unReadBroadInfor = [[NSMutableDictionary alloc] initWithCapacity:10];
    _zibarString = nil;
    _languageDictionary=[[NSMutableDictionary alloc]initWithCapacity:10];
    _Messagetype=MessageTypeStand;
    _keyArr=[[NSMutableArray alloc]initWithCapacity:10];
    _valueArr=[[NSMutableArray alloc]initWithCapacity:10];
    _messageRadioDictionary=[[NSMutableDictionary alloc]init];
    _unLoginArr=[[NSMutableArray alloc]initWithCapacity:10];
    _boolArr=[[NSMutableArray alloc]initWithCapacity:10];
    _emiNameArr=[[NSMutableArray alloc]initWithObjects:@"打怪兽",@"嘟嘟嘴",@"多变",@"饿了",@"高兴",@"歌王",@"好烦啊",@"加油",@"惊讶",@"可爱",@"可怜",@"麦霸",@"怒火",@"饶命",@"撒娇",@"睡觉",@"痛苦",@"羞羞脸",@"阴谋",@"眨眼",@"发大财",@"喷饭",@"炸飞了",@"凄凉",@"T台秀",@"读书",@"扭屁股",@"舞蹈",@"得意",@"运动",@"救命",@"滚远点",@"江南舞",@"走你", nil];
    
    _emiLanguageArr=[[NSMutableArray alloc]initWithObjects:NSLocalizedString(@"smileItem", nil),NSLocalizedString(@"smileItem1", nil),NSLocalizedString(@"smileItem2", nil),NSLocalizedString(@"smileItem3", nil),NSLocalizedString(@"smileItem4", nil),NSLocalizedString(@"smileItem5", nil),NSLocalizedString(@"smileItem6", nil),NSLocalizedString(@"smileItem7", nil),NSLocalizedString(@"smileItem8", nil),NSLocalizedString(@"smileItem9", nil),NSLocalizedString(@"smileItem10", nil),NSLocalizedString(@"smileItem12", nil),NSLocalizedString(@"smileItem13", nil),NSLocalizedString(@"smileItem15", nil),NSLocalizedString(@"smileItem16", nil),NSLocalizedString(@"smileItem17", nil),NSLocalizedString(@"smileItem19", nil),NSLocalizedString(@"smileItem20", nil),NSLocalizedString(@"smileItem22", nil),NSLocalizedString(@"smileItem23", nil),NSLocalizedString(@"smileItem24", nil),NSLocalizedString(@"smileItem25", nil),NSLocalizedString(@"smileItem26", nil),NSLocalizedString(@"smileItem27", nil),NSLocalizedString(@"smileItem28", nil),NSLocalizedString(@"smileItem29", nil),NSLocalizedString(@"smileItem30", nil),NSLocalizedString(@"smileItem31", nil),NSLocalizedString(@"smileItem32", nil),NSLocalizedString(@"smileItem33", nil),NSLocalizedString(@"smileItem34", nil),NSLocalizedString(@"smileItem35", nil),NSLocalizedString(@"smileItem36", nil),NSLocalizedString(@"smileItem37", nil), nil];
    
    _agreeList=[[NSMutableArray alloc]initWithCapacity:10];
    _talkArr=[[NSMutableArray alloc]initWithCapacity:10];
    _readedUserArray = [[NSMutableArray alloc]initWithCapacity:10];
    _bubbleNameDic = [[NSMutableDictionary alloc]initWithCapacity:20];
    
    NSDateFormatter * formatter = [[[NSDateFormatter alloc]init] autorelease];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    _lastShowwingTime = [[formatter dateFromString:@"1900-01-01 00:00:00"] retain];
    _secondaryTalkPeople = [[NSMutableArray alloc] initWithCapacity:10];
    
    _lastSayHiUserInfoDic = [[NSMutableDictionary alloc]initWithCapacity:10];
    
    [self performSelectorInBackground:@selector(setSmileViewInBackGround) withObject:nil];
    
    if(![FileManager fileExistsAtPath:DataCachePath])
        [FileManager createDirectoryAtPath:DataCachePath withIntermediateDirectories:NO attributes:nil error:nil];
    
    _dataBase = [[FMDatabase alloc] initWithPath:DataBasePath];
    if(![_dataBase open])
    {
        [_dataBase close];
        _dataBase = nil;
    }
}

//调用后台线程创建表情键盘
-(void)setSmileViewInBackGround
{
    [self performSelectorOnMainThread:@selector(setSmileView) withObject:nil waitUntilDone:YES];
}

//初始化发消息时的表情
-(void)setSmileView
{
    self.smileViewBackup = [[[BanBu_SmileView alloc] initWithFrame:CGRectMake(0, __MainScreen_Height-44, 320, SmileViewDefaultHeight)] autorelease];
    [self.smileViewBackup.pageControl setFrame:CGRectMake(0, 164, 320, 10)];
    self.smileViewBackup.type = SmileViewSmileType;
    
    self.emoKeyboard = [[[BanBu_EmoKeyboard alloc]init] autorelease];
    self.emoKeyboard.view.frame = CGRectMake(0, 0, 320, 216);
    self.emoKeyboard.view.hidden = NO;
    
    BanBu_ChatBackgroundSettingViewController * chatBG =  [[BanBu_ChatBackgroundSettingViewController alloc] init];
    [chatBG getDefault];
    [chatBG release];
    BanBu_BubbleViewController * bubble= [[[BanBu_BubbleViewController alloc]init] autorelease];
    [bubble getDefault];
    
    [self getBubbleNames];
}

//获取气泡的文件夹名字和id
-(void)getBubbleNames
{
    NSString * fileName = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"BubbleImageFolder"];
    
    NSString * bubbleDirPath;
    NSDictionary * bubbleNameDic = [NSDictionary dictionaryWithContentsOfFile:[fileName stringByAppendingPathComponent:@"bubbleInfo.plist"]];
    
    for (int i =0 ; i < bubbleNameDic.count; i++)
    {
        NSString * bubbleName =[NSString stringWithFormat:@"bubble_%d",i];
        bubbleDirPath = [fileName stringByAppendingPathComponent:bubbleName];
        bubbleDirPath = [bubbleDirPath stringByAppendingPathComponent:@"aio_user_bg_nor@2x.png"];
        
        UIImage * image = [UIImage imageWithContentsOfFile:bubbleDirPath];
        if (!image)
        {
            continue;
        }
        [MyAppDataManager.bubbleNameDic setValue:bubbleName forKey:[NSString stringWithFormat:@"%d",i]];
    }
}


+ (AppDataManager *)sharedAppDataManager;
{
    @synchronized(self){
        if(sharedAppDataManager == nil){
            sharedAppDataManager = [[self alloc] init];
            [sharedAppDataManager initRaysource];
        }
    }
    return sharedAppDataManager;
}

-(void)setMessagetype:(MessageType)Messagetype
{
    if(Messagetype==_Messagetype)
        return;
    _Messagetype=Messagetype;
}

//通过对方的UserID获取聊天记录表名
-(NSString *)getTableNameForUid:(NSString *)uid
{
    //修改数据库聊天记录文件后的返回值
    return [NSString stringWithFormat:@"chat_%@_%d",self.useruid,[uid integerValue]%10];
}

#pragma mark - 全局接受消息
//全局接受消息时，写入多人多条消息
-(void)writeToDB:(NSDictionary *)people
{//人和消息的数组
    NSMutableDictionary *changPeople = [NSMutableDictionary dictionaryWithDictionary:people];
    [changPeople setValue:[NSNumber numberWithBool:NO] forKey:KeyMe];
    [changPeople setValue:[NSNumber numberWithInteger:ChatStatusNone] forKey:KeyStatus];
    
    //写入聊天记录表是必须的（一、多条消息均可）
    //记录未读消息
    NSInteger effectiveNum = [self writeToDialogDB:changPeople];//返回值大于0说明有有效消息，否则来的消息都是无效消息，不需要更新对话表
    NSLog(@"记录消息:%@",people);
    NSLog(@"记录未读消息数量:%d",effectiveNum);
    if(effectiveNum>0)
    {
        //更新对话表。当对话表中没有该人的记录时，插入该人的记录，有记录时，执行下一步更新操作
        if (![self initTalkPeopleOne:changPeople withEffectiveNum:effectiveNum])
        {
            [self writeToTalkPeopleOne:changPeople withEffectiveNum:effectiveNum];
        }
    }
}
#pragma mark - 对话表各种操作

//初始化talkPeople1127表
//editBy ：Wang Xj at 2013-7-8 18：14：00 对话列表 修改（减少字段，以前存在该表的就不再减少，不存在该表的，即新创建改表的只创建下面的字段）
-(void)initTalkPeopleDB
{
    if(![_dataBase goodConnection])
        [_dataBase open];
    
    if(![_dataBase tableExists:TALKPEOPLES])
    {
        NSDictionary *queryDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                  DBFieldType_TEXT,    KeyFromUid,
                                  
                                  DBFieldType_TEXT,    KeyContent,
                                  DBFieldType_TEXT,    KeyStime,
                                  DBFieldType_INTEGER, KeyUnreadNum,
                                  DBFieldType_INTEGER, KeyType,
                                  DBFieldType_TEXT,    KeyOnLinetime,
                                  
                                  DBFieldType_BOOL,    KeyMe,
                                  DBFieldType_INTEGER, KeyStatus,
                                  DBFieldType_TEXT,    KeyLevel,    //用户的级别，如果是0或空，则表示直接在对话中显示，如果是其他的userid，则说明是在该文件夹下的：如：好友验证id为600，系统通知为400
                                  
                                  DBFieldType_TEXT,    keyPersonalInfo,//存放uface、pname、gender、age、userlevel；
                                  DBFieldType_TEXT,    KeyDmeter,
                                  DBFieldType_INTEGER, KeyShowContent,//对话列表中富媒体显示的内容
                                  DBFieldType_TEXT,    KeyStimeIndex, //时间索引，查询时使用
                                  nil];
        
        NSString *queryCreateTable = [NSString stringWithFormat:@"CREATE TABLE %@ (%@, PRIMARY KEY(userid ASC))",TALKPEOPLES,[self getPar1StrFromDic:queryDic]];
        BOOL f = [_dataBase executeUpdate:queryCreateTable];
        
        NSString *queryIndex = [NSString stringWithFormat:@"CREATE INDEX _userid ON %@(stime);",TALKPEOPLES];
        BOOL ff = [_dataBase executeUpdate:queryIndex];
        
        if(!(ff && f))
        {
            NSLog(@"initTalkPeopleDB：%@",[[_dataBase lastError] description]);
        }
    }
}

#pragma  - 往对话表中插入数据
//对话表中不存在该人，就插入对话表内
//editBy ：Wang Xj at 2013-7-8 18：14：00
-(BOOL)initTalkPeopleOne:(NSDictionary *)people withEffectiveNum:(NSInteger)effectiveNum
{
    [self initTalkPeopleDB];
  
    //查看数据库中是否有该人
    NSString *uid = [people valueForKey:KeyFromUid];
    //07/30 by 尹林 查找TALKPEOPLES表中userid的数量（count），并按照_value变量返回
    NSString *query = [NSString stringWithFormat:@"SELECT count(userid) AS _value FROM %@ WHERE userid=%@",TALKPEOPLES,uid];
    FMResultSet *rs = [_dataBase executeQuery:query];
    
    NSInteger count = 0;
    
    while ([rs next])
    {
        //取出_value的值
        count = [rs intForColumn:@"_value"];
    }

    BOOL new = (count < 1);
    //TALKPEOPLES（聊天列表不是与某人的聊天详情）之前不存在与此人的聊天记录
    if (new)
    {
        //创建sql语句
        NSString *query = [NSString stringWithFormat:@"INSERT INTO %@ (userid,content,stime,unreadnum,type,ltime,me,status,level,userinfor,dmeter,showcontent,stimeIndex) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",TALKPEOPLES];
        
        NSArray * msgList = [people valueForKey:@"msglist"];
        
        NSDictionary *amsgDic = [NSDictionary dictionaryWithDictionary:[msgList lastObject]];
        
        for (int i = msgList.count-1; i>=0; i--)
        {
            amsgDic = [msgList objectAtIndex:i];
            if ([self checkIsReceiveSystemMessage:amsgDic])
            {
                break;
            }
            else if (i==0)
            {
                //不更新对话列表直接返回YES
                return YES;
            }
        }
        
        NSString * level = @"600";//默认是600号，如果是userid是400、500、600level为@""
        
        if ([[people valueForKey:KeyMe] boolValue])
        {
            level = @"0";
            //将该用户id添加到已聊过天表中，因为这是主动发的消息,（以后打招呼不显示在打招呼列表中）
            [self insertChatTable:VALUE(KeyFromUid, people)];
        }
        else if ([VALUE(KeyFromUid, people) integerValue]<1000)
        {
            level = @"0";
        }
        //检查用户本次消息是否是打招呼,是打招呼：返回YES；不是打招呼：返回NO
        else if (![self checkDialogIsSayHi:VALUE(KeyFromUid, people)])
        {//是好友关系，level为0，顶级
            level = @"0";
        }
        //包装完整的对话消息
        NSDictionary * talkDic = [self getWholeTalk:people];
        
        if (talkDic==nil)
        {
            return NO;
        }
        
        //往数据库中插入数据
        BOOL s = [_dataBase executeUpdate:query,
                  VALUE(KeyFromUid, people),
                  VALUE(KeyContent, talkDic),
                  VALUE(KeyStime, talkDic),
                  [NSNumber numberWithInt:effectiveNum], //keynumber
                  [NSNumber numberWithInteger:[VALUE(KeyType, talkDic) integerValue]], //消息类型 （0~6 : text、image、location、sound、emi、hints、video）
                  VALUE(KeyOnLinetime, people),
                  [NSNumber numberWithBool:[VALUE(KeyMe, people) boolValue]],//  keyme ：别人发的是0；我发的是1
                  [NSNumber numberWithInt:2],   //ChatStatus：ChatStatusNone
                  level,        //好友验证，二级目录
                  VALUE(keyPersonalInfo, talkDic),
                  VALUE(KeyDmeter, talkDic),
                  VALUE(KeyShowContent, talkDic),
                  VALUE(KeyStimeIndex, talkDic)
                  ];
        if(!s)
        {
            NSLog(@"initTalkPeopleOne:database action error:%@",[[_dataBase lastError] description]);
            new = NO;
        }
        else
        {
            //判断一下当前对话是否为打招呼，如果是打招呼就改，如果不是就不改
            if ([level integerValue]<100)
            {
                //不是打招呼(level是@"0")，所以是对话列表中多一条，打招呼条数不变
                MyAppDataManager.totalLoadedPeopleNum +=1;
                return new;
            }
            
            //是打招呼，更新打招呼最有一条显示内容
            //更新600号（好友验证帐号）系统账号的stime为当前的stime，确保对话表显示正常
            NSDictionary * amsg = [NSDictionary dictionaryWithObjectsAndKeys:
                                   VALUE(KeyFromUid, people),              KeyFromUid,
                                   VALUE(KeyContent, talkDic),              KeyContent,
                                   VALUE(KeyStime, talkDic),                KeyStime,
                                   [NSNumber numberWithInteger:[VALUE(KeyType, talkDic) integerValue]],    KeyType,
                                   [NSNumber numberWithBool:NO],            KeyMe,
                                   [NSNumber numberWithInt:2],              KeyStatus,
                                   [NSNumber numberWithInt:[[people valueForKey:KeyMsglist] count]],              KeyUnreadNum,
                                   VALUE(KeyShowContent, talkDic),          KeyShowContent,
                                   VALUE(KeyOnLinetime, people),           KeyOnLinetime,
                                   nil];
            
            if(![self initSystemUser:@"600" ByMsg:amsg])
            {
                [self updateLastDialogBySayHi:amsg];
            }
        }
    }
    
    return new;
}

#pragma  - 将别人发送过来的消息写入到对话列表的数据库
//更新表talkPeople1127的人（更新所有字段）
-(void)writeToTalkPeopleOne:(NSDictionary *)dataDic withEffectiveNum:(NSInteger)effectiveNum
{
    if(![_dataBase goodConnection])
        [_dataBase open];
    
    NSArray * msgList = [dataDic valueForKey:@"msglist"];
    
    NSDictionary *amsgDic = [NSDictionary dictionaryWithDictionary:[msgList lastObject]];
    
    for (int i = msgList.count-1; i>=0; i--)
    {
        amsgDic = [msgList objectAtIndex:i];
        if ([self checkIsReceiveSystemMessage:amsgDic])
        {
            break;
        }
        else if (i==0)
        {
            //不更新对话列表直接返回YES
            return;
        }
    }
    
    NSString *query = [NSString stringWithFormat:@"UPDATE %@ SET unreadnum = unreadnum +?,content=?,stime=?,type=?,ltime=?,me=?,status=?,showcontent=?,userinfor=?,dmeter=?,stimeIndex =? WHERE userid=?",TALKPEOPLES];
    
    NSDictionary * talkDic = [self getWholeTalk:dataDic];

    if (talkDic==nil)
    {
        return;
    }
    
    BOOL s = [_dataBase executeUpdate:query,
              [NSNumber numberWithInt:effectiveNum], //keynumber
              VALUE(KeyContent, talkDic),
              VALUE(KeyStime, talkDic),
              [NSNumber numberWithInteger:[VALUE(KeyType, talkDic) integerValue]],
              VALUE(KeyOnLinetime, dataDic),
              [NSNumber numberWithBool:NO], //  keyme ：别人发的是0；我发的是1
              [NSNumber numberWithInt:4],   //ChatStatus：ChatStatusNone
              VALUE(KeyShowContent, talkDic),
              VALUE(keyPersonalInfo, talkDic),
              VALUE(KeyDmeter, talkDic),
              VALUE(KeyStimeIndex, talkDic),
              [dataDic valueForKey:KeyFromUid]
              ];
    if(!s)
    {
        NSLog(@"writeToTalkPeopleOne:database action error:%@",[[_dataBase lastError] description]);
    }
    else
    {
        //判断一下当前对话是否为打招呼，如果是打招呼就改，如果不是就不改
        if ([VALUE(KeyFromUid, dataDic) integerValue]<1000||(![self checkDialogIsSayHi:VALUE(KeyFromUid, dataDic)]))
        {
            //看一下level是不是@“0”，不是@“0”的时候看看两人的关系，如果是好友就需要修改level的值为@“0”；
            if ([self judgeRelationship:VALUE(KeyFromUid, dataDic)])
            {//是好友
                NSString * level = [self getLevelByUserID:VALUE(KeyFromUid, dataDic)];
                if ([level integerValue] != 0)//原来不是好友，现在是好友了，但是level还没变过来呢，
                {
                    NSDictionary * amsg = [self getTheLastSayHiUser];
                    if ([[amsg valueForKey:KeyFromUid] isEqualToString:VALUE(KeyFromUid, dataDic)])
                    {
                        [self updateDialogUserLevel:VALUE(KeyFromUid, dataDic) toLevel:@"0"];
                        
                        [self updateLastDialogBySayHi:amsg];
                    }
                }
            }
            return;
        }
        
        //更新600号（好友验证帐号）系统账号的stime为当前的stime，确保对话表显示正常
        NSDictionary * amsg = [NSDictionary dictionaryWithObjectsAndKeys:
                               VALUE(KeyFromUid, dataDic),              KeyFromUid,
                               VALUE(KeyContent, talkDic),              KeyContent,
                               VALUE(KeyStime, talkDic),                KeyStime,
                               [NSNumber numberWithInteger:[VALUE(KeyType, talkDic) integerValue]],    KeyType,                               
                               [NSNumber numberWithBool:NO],            KeyMe,
                               [NSNumber numberWithInt:4],              KeyStatus,
                               [NSNumber numberWithInt:[[dataDic valueForKey:KeyMsglist] count]],              KeyUnreadNum,
                               VALUE(KeyShowContent, talkDic),          KeyShowContent,
                               VALUE(KeyOnLinetime, dataDic),           KeyOnLinetime,
                               nil];
        
        if (![self initSystemUser:@"600" ByMsg:amsg])
        {
            [self updateLastDialogBySayHi:amsg];
        }
    }
}
#pragma mark - 将自己发送的消息写入到对话列表数据库
-(void)writeToTalkPeopleOne:(NSDictionary *)dataDic withEffectiveNum:(NSInteger)effectiveNum withLevel:(NSString *)level
{
    if(![_dataBase goodConnection])
        [_dataBase open];
    
    NSString *query = [NSString stringWithFormat:@"UPDATE %@ SET unreadnum = unreadnum +?,content=?,stime=?,type=?,ltime=?,me=?,status=?,showcontent=?,userinfor=?,dmeter=?,level=?,stimeIndex=? WHERE userid=?",TALKPEOPLES];
    
    NSDictionary * talkDic = [self getWholeTalk:dataDic];
    
    if (talkDic==nil)
    {
        return;
    }
    
    BOOL s = [_dataBase executeUpdate:query,
              [NSNumber numberWithInt:effectiveNum], //keynumber
              VALUE(KeyContent, talkDic),
              VALUE(KeyStime, talkDic),
              [NSNumber numberWithInteger:[VALUE(KeyType, talkDic) integerValue]],
              VALUE(KeyOnLinetime, dataDic),
              [NSNumber numberWithBool:[VALUE(KeyMe, dataDic) boolValue]], //keyme ：别人发的是0；我发的是1
              [NSNumber numberWithInt:2],   //ChatStatus：ChatStatusNone
              VALUE(KeyShowContent, talkDic),
              VALUE(keyPersonalInfo, talkDic),
              VALUE(KeyDmeter, talkDic),
              level,
              VALUE(KeyStimeIndex, talkDic),
              [dataDic valueForKey:KeyFromUid]
              ];
    if(!s)
    {
        NSLog(@"writeToTalkPeopleOne:database action error:%@",[[_dataBase lastError] description]);
    }
}

#pragma mark - 包装完整的对话消息
//包装完整的对话消息
-(NSDictionary *)getWholeTalk:(NSDictionary *)dataDic
{
    NSArray * msgList = [dataDic valueForKey:@"msglist"];
    
    NSDictionary *amsgDic = [NSDictionary dictionaryWithDictionary:[msgList lastObject]];
    
    NSDictionary *saysDic=[AppComManager getAMsgFrom64String:[amsgDic valueForKey:KeySays]];
    
    NSArray *mapArr = typeArrDefine;
    
    NSInteger msgType = [mapArr indexOfObject:VALUE(KeyType, saysDic)];
    
    if (msgType>8)//如果消息类型超出现有类型，默认为文本
    {
        msgType = 0;
    }
    
//    if (msgType == 5)
//    {
//        if ([[dataDic valueForKey:@"msglist"] count]<2)
//        {
//            return nil;
//        }
//        
//        amsgDic = [NSDictionary dictionaryWithDictionary:[[dataDic valueForKey:@"msglist"] objectAtIndex:[[dataDic valueForKey:@"msglist"] count]-2]];
//        saysDic = [AppComManager getAMsgFrom64String:[amsgDic valueForKey:KeySays]];
//        msgType = [mapArr indexOfObject:VALUE(KeyType, saysDic)];
//        if (msgType>8)//如果消息类型超出现有类型，默认为文本
//        {
//            msgType = 0;
//        }
//    }
    
    //发送时间
    NSString * stime =  [self getStime:amsgDic];
    if ([[dataDic valueForKey:KeyMe] boolValue])
    {
        stime = [amsgDic valueForKey:KeyStime];
    }
    
    NSString * content = VALUE(KeyContent, saysDic);
    
    if ([VALUE(KeyShowFrom, saysDic) isEqualToString:@"snap"])
    {
        content = NSLocalizedString(@"snapText", nil);
    }
    else if ([VALUE(KeyShowFrom, saysDic) isEqualToString:@"collect"]||[VALUE(KeyShowFrom, saysDic) isEqualToString:@"store"])
    {
        content = NSLocalizedString(@"emitionType", nil);
    }
    
    if (content == nil || [content isEqualToString:@""])
    {
        return nil;
    }
    
    content = [[CJSONSerializer serializer] serializeObject:content];
    content = [[content dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    NSString * showContent = @"";
    if ((msgType == ChatCellTypeSpecialText) || (msgType == CHatCellTYpeHints))
    {
        showContent = VALUE(KeyShowContent, saysDic);
        if (showContent!= nil)
        {
            showContent = [[CJSONSerializer serializer] serializeObject:showContent];
            showContent = [[showContent dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
        }
    }
    
    //userinfo(uface、pname、gender、age)
    NSDictionary * userinfoDic = [self getUserinfo:VALUE(KeyFromUid, dataDic)];
    NSString * userinfo = @"";
    if (userinfoDic)
    {
        userinfo = [[CJSONSerializer serializer] serializeDictionary:userinfoDic];
        userinfo = [[userinfo dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    }
    //dmeter
    NSString * dmeter = [userinfoDic valueForKey:KeyDmeter];
    if (dmeter == nil)
    {
        dmeter = @"";
    }
    
    //stimeIndex
    NSString * stimeIndex = [self getStimeIndex];
    
    NSMutableDictionary * talkDic = [NSMutableDictionary dictionaryWithCapacity:10];
    [talkDic setValue:content forKey:KeyContent];
    [talkDic setValue:showContent forKey:KeyShowContent];
    [talkDic setValue:userinfo forKey:keyPersonalInfo];
    [talkDic setValue:dmeter forKey:KeyDmeter];
    [talkDic setValue:stime forKey:KeyStime];
    [talkDic setValue:stimeIndex forKey:KeyStimeIndex];
    [talkDic setValue:[NSNumber numberWithInt:msgType] forKey:KeyType];
    
    return talkDic;
}

//addBy:Wang Xj at 2013-7-3 15:01
//获取全局未读消息数量
-(NSInteger)getBadgeValue
{
    //统计未读数量，显示在气泡里
    NSString * query = [NSString stringWithFormat:@"SELECT SUM(unreadnum) AS _value FROM %@ WHERE userid <> 600 AND userinfor IS NOT NULL",TALKPEOPLES];
    
    if(![_dataBase goodConnection])
        [_dataBase open];
    FMResultSet * rs = [_dataBase executeQuery:query];
    NSInteger badgeCount = 0;
    
    while ([rs next])
    {
        badgeCount = [rs intForColumn:@"_value"];
    }
    return badgeCount;
}

//这是原来的版本，这里不用了，把名字改成getAllBadgeValue了，说不定以后还要改回来
-(NSInteger)getAllBadgeValue
{
    //统计未读数量，显示在气泡里
    NSString * query = [NSString stringWithFormat:@"SELECT SUM(unreadnum) AS _value FROM %@ WHERE level = '0';",TALKPEOPLES];
    
    if(![_dataBase goodConnection])
        [_dataBase open];
    FMResultSet * rs = [_dataBase executeQuery:query];
    NSInteger badgeCount = 0;
    
    while ([rs next])
    {
        badgeCount = [rs intForColumn:@"_value"];
    }
    return badgeCount;
}

#pragma  - 更新点对点对话中最后一条信息在对话表中的存储
//在点对点接受消息时，要更新对话列表中该人的最后一条消息content和发出时间，谁发的keyme、消息的状态（发送中、送达、失败），此处局部更新
-(void)setTalkPeopleOne:(NSDictionary *)updataDic
{
    if(![_dataBase goodConnection])
        [_dataBase open];
    
    //漏掉了keytype，添上了。
    NSString *query = [NSString stringWithFormat:@"UPDATE %@ SET content=?,stime=?,me=?,status=?,type=?, unreadnum=?,showcontent = ? WHERE (userid=?)",TALKPEOPLES];
    NSNumber * type;
    type = [updataDic valueForKey:KeyType];
    NSArray *mapArr = contentArrDefine;
    
    
    if ([[updataDic objectForKey:KeyType] isKindOfClass:[NSString class]])
    {
        if ([[updataDic valueForKey:KeyType] isEqualToString:@"text"])
        {
            type = [NSNumber numberWithInt:0];
        }
        else if ([[updataDic valueForKey:KeyType] isEqualToString:@"image"])
        {
            type = [NSNumber numberWithInt:1];
            [updataDic setValue:[mapArr objectAtIndex:1] forKey:KeyContent];
        }
        else if ([[updataDic valueForKey:KeyType] isEqualToString:@"location"])
        {
            type = [NSNumber numberWithInt:2];
            [updataDic setValue:[mapArr objectAtIndex:2] forKey:KeyContent];
        }
        else if ([[updataDic valueForKey:KeyType] isEqualToString:@"sound"])
        {
            type = [NSNumber numberWithInt:3];
            [updataDic setValue:[mapArr objectAtIndex:3] forKey:KeyContent];
        }
        else if([[updataDic valueForKey:KeyType] isEqualToString:@"emi"])
        {
            type = [NSNumber numberWithInt:4];
            [updataDic setValue:[mapArr objectAtIndex:4] forKey:KeyContent];
        }
        else if([[updataDic valueForKey:KeyType] isEqualToString:@"video"])
        {
            type = [NSNumber numberWithInt:6];
            [updataDic setValue:[mapArr objectAtIndex:6] forKey:KeyContent];
        }
        else if ([[updataDic valueForKey:KeyType] isEqualToString:@"magicGif"])
        {
            type = [NSNumber numberWithInt:7];
            [updataDic setValue:[mapArr objectAtIndex:7] forKey:KeyContent];
        }
        else if ([[updataDic valueForKey:KeyType] isEqualToString:@"specialText"])
        {
            type = [NSNumber numberWithInt:8];
            [updataDic setValue:[mapArr objectAtIndex:8] forKey:KeyContent];
        }
        else
        {
            type = [NSNumber numberWithInt:0];
        }
    }
    
    //如果消息类型超出现有消息类型，默认为文本
    if ([type intValue]>8)
    {
        type = 0;
    }
    else if ([type intValue] == 8)
    {
        
    }
    
    //显示的内容
    NSString * content = VALUE(KeyContent, updataDic);
    
    content = [[CJSONSerializer serializer] serializeObject:content];
    content = [[content dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    //要显示在对话列表的内容(仅针对富媒体形式)
    NSString * showContent = @"";
    if ([type intValue] == ChatCellTypeSpecialText)
    {
        showContent = VALUE(KeyShowContent, updataDic);
        if (showContent != nil )
        {
            showContent = [[CJSONSerializer serializer] serializeObject:showContent];
            showContent = [[showContent dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
        }
        else
        {
            showContent = @"";
        }
    }
    
    BOOL s = [_dataBase executeUpdate:query,
              content,
              [updataDic valueForKey:@"stime"],
              [NSNumber numberWithBool:[[updataDic valueForKey:@"me"] integerValue]],
              [NSNumber numberWithInt:[[updataDic valueForKey:@"status"] integerValue]],
              type,
              [NSNumber numberWithInteger:0],
              showContent,
              [updataDic valueForKey:@"userid"]
              ];
    if(!s)
    {
        NSLog(@"setTalkPeopleOne:database action error:%@",[[_dataBase lastError] description]);
    }
    
    NSString * tableName = [self getTableNameForUid:[updataDic valueForKey:KeyFromUid]];
    NSString * updateMediaStatusQuery = [NSString stringWithFormat:@"UPDATE %@ SET mediastatus=? WHERE chatid=?",tableName];
    
    BOOL bl = [_dataBase executeUpdate:updateMediaStatusQuery,[NSNumber numberWithInt:[[updataDic valueForKey:KeyMediaStatus] integerValue]],[updataDic valueForKey:KeyChatid]];
    
    if (!bl)
    {
        
    }
}

//阅后即焚消息消除时，更新对话表最后一条消息的内容（包括stime）
-(void)setTalkPeopleOneNOUnread:(NSDictionary *)updataDic
{
    if(![_dataBase goodConnection])
        [_dataBase open];
    //漏掉了keytype，添上了。
    
    NSString *query = [NSString stringWithFormat:@"UPDATE %@ SET content=?,stime=?,me=?,status=?,type=? WHERE (userid=?)",TALKPEOPLES];
    NSNumber * type = [updataDic valueForKey:KeyType];
    
    //如果消息类型超出现有消息类型，默认为文本
    if ([type intValue]>8)
    {
        type = [NSNumber numberWithInt:0];
    }
    
    NSString * content = VALUE(KeyContent, updataDic);
    
    content = [[CJSONSerializer serializer] serializeObject:content];
    content = [[content dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    BOOL s = [_dataBase executeUpdate:query,
              content,
              [updataDic valueForKey:@"stime"],
              [NSNumber numberWithBool:[[updataDic valueForKey:@"me"] integerValue]],
              [NSNumber numberWithInt:[[updataDic valueForKey:@"status"] integerValue]],
              type,
              [updataDic valueForKey:@"userid"]
              ];
    if(!s)
    {
        NSLog(@"setTalkPeopleOne:database action error:%@",[[_dataBase lastError] description]);
    }
}

//阅后即焚消息消除时，更新对话表最后一条消息的内容（不包括stime）
-(void)setTalkPeopleOneNOStime:(NSDictionary *)updataDic
{
    if(![_dataBase goodConnection])
        [_dataBase open];
    //漏掉了keytype，添上了。
    
    NSString *query = [NSString stringWithFormat:@"UPDATE %@ SET content=?,status=?,type=? WHERE (userid=?)",TALKPEOPLES];
    NSNumber * type = [updataDic valueForKey:KeyType];
    
    //如果消息类型超出现有消息类型，默认为文本
    if ([type intValue]>8)
    {
        type = [NSNumber numberWithInt:0];
    }
    
    NSString * content = VALUE(KeyContent, updataDic);
    
    content = [[CJSONSerializer serializer] serializeObject:content];
    content = [[content dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    BOOL s = [_dataBase executeUpdate:query,
              content,
              [NSNumber numberWithInt:[[updataDic valueForKey:@"status"] integerValue]],
              type,
              [updataDic valueForKey:@"userid"]
              ];
    if(!s)
    {
        NSLog(@"setTalkPeopleOne:database action error:%@",[[_dataBase lastError] description]);
    }
}

-(void)setUnreadNumber:(NSInteger)number With:(NSString *)userid
{
    NSString *query = [NSString stringWithFormat:@"UPDATE %@ SET unreadnum=? WHERE (userid=?);",TALKPEOPLES];
    BOOL s = NO;
    
    if (userid == nil)
    {
        query = [NSString stringWithFormat:@"UPDATE %@ SET unreadnum= ?  WHERE (userid NOT IN (%@))",TALKPEOPLES,@"500"];
        s = [_dataBase executeUpdate:query,[NSNumber numberWithInt:number]];
    }
    else
    {
        s = [_dataBase executeUpdate:query,
             [NSNumber numberWithInt:number],
             userid
             ];
    }
    
    if(!s)
    {
        NSLog(@"setUnreadNumber database action error:%@",[[_dataBase lastError] description]);
    }
    
    [MyAppDataManager.appChatController.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
}

//清除未读标记
-(NSInteger)clearUnReadDialogsNumber:(NSString *)chatUID
{
    if(![_dataBase goodConnection])
        [_dataBase open];
    
    NSString *query = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE userid=%@",TALKPEOPLES,chatUID];
    
    FMResultSet * rs = [_dataBase executeQuery:query];
    
    NSInteger unReadNumber = 0;
    while ([rs next])
    {
        unReadNumber = [rs intForColumn:KeyUnreadNum];
    }
    
    return unReadNumber;
}

//将拉入黑名单的人的对话删除
-(void)deleteBlackDialog:(NSString *)userID
{
    if (![_dataBase goodConnection])
    {
        [_dataBase open];
    }
    
    NSString * updateQuery = [NSString stringWithFormat:@"DELETE FROM %@ WHERE userid in (%@)",TALKPEOPLES,userID];
    
    BOOL s1 = [_dataBase executeUpdate:updateQuery];
    
    if (!s1)
    {
        NSLog(@"deleteBlackDialog 删除一条聊天记录失败database action error:%@",[[_dataBase lastError] description]);
    }
}

//当对话界面的消息已读状态与聊天信息最后一条信息的已读状态不一致时要更新对话表（注：该消息必须是自己发的）
-(void)updateStstus:(NSString *)userID number:(NSNumber *)number
{
    if (![_dataBase goodConnection])
    {
        [_dataBase open];
    }
    
    NSString * dialogQuery = [NSString stringWithFormat:@"UPDATE %@ SET status = %@ WHERE userid = %@",TALKPEOPLES,number,userID];
    
    BOOL s1 = [_dataBase executeUpdate:dialogQuery];
    
    if (!s1)
    {
        NSLog(@"updateStstus database action error:%@",[[_dataBase lastError] description]);
    }
}

//更新重发消息的发送时间
-(void)updateStime:(NSDictionary *)amsg
{
    if (![_dataBase goodConnection])
    {
        [_dataBase open];
    }
    NSString * tableName = [self getTableNameForUid:VALUE(KeyFromUid, amsg)];
    NSString * dialogQuery = [NSString stringWithFormat:@"UPDATE %@ SET stime = '%@',stimeIndex='%@',height=%@,showtime=%@ WHERE chatid = '%@'",tableName,VALUE(KeyStime, amsg),VALUE(KeyStimeIndex, amsg),VALUE(KeyHeight, amsg),VALUE(KeyShowtime, amsg),VALUE(KeyChatid, amsg)];
    NSLog(@"dialogQuery:%@",dialogQuery);
    BOOL s1 = [_dataBase executeUpdate:dialogQuery];
    
    if (!s1)
    {
        NSLog(@"updateStime database action error:%@",[[_dataBase lastError] description]);
    }

}

#pragma mark - 转发
//转发：更新对话表，从最新对话转发
-(void)writeToTalkPeopleAll:(NSDictionary *)amsg To:(NSArray *)userList
{
    if (![_dataBase goodConnection])
    {
        [_dataBase open];
    }
    
    //获取转发的人的个人资料
    NSString * useridList = [userList componentsJoinedByString:@","];
    NSDictionary * userInfoDic = [self getUserinfoDic:useridList];
    
    //先从对话表中删除这些人的记录
    NSString * deleteQuery = [NSString stringWithFormat:@"DELETE FROM %@ WHERE userid IN(%@)",TALKPEOPLES,useridList];
    
    BOOL bl = [_dataBase executeUpdate:deleteQuery];
    if (!bl)
    {
        NSLog(@"writeToTalkPeopleAll 删除对话表失败 database action error:%@",[[_dataBase lastError] description]);
    }
    else
    {
        NSString * content = VALUE(KeyContent, amsg);
        NSString * showContent = @"";
        
        content = [[CJSONSerializer serializer] serializeObject:content];
        content = [[content dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
        
        //消息类型
        NSInteger msgType = 0;
        
        if ([VALUE(KeyType, amsg) isKindOfClass:[NSNumber class]])
        {
            msgType = [VALUE(KeyType, amsg) integerValue];
        }
        else
        {
            NSArray *mapArr = typeArrDefine;
        
            msgType = [mapArr indexOfObject:VALUE(KeyType, amsg)];
        }
        
        //显示文本
        if (msgType == ChatCellTypeSpecialText)
        {
            showContent = VALUE(KeyShowContent, amsg);
            if (showContent!= nil )
            {
                showContent = [[CJSONSerializer serializer] serializeObject:showContent];
                showContent = [[showContent dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
            }
        }
        
        //插入对话表中数据
        NSMutableString * query =[NSMutableString stringWithFormat:@"INSERT INTO %@ (userid,content,stime,unreadnum,type,me,status,level,userinfor,dmeter,showcontent,stimeIndex)   ",TALKPEOPLES];
        for (NSString * userid in userList)
        {
            NSDictionary * userInfoDictionary = [userInfoDic valueForKey:userid];

            //dmeter
            NSString * dmeter = [userInfoDictionary valueForKey:KeyDmeter];
            NSString * userInfo = [userInfoDictionary valueForKey:keyPersonalInfo];
            if(dmeter.length == 0)
            {
                dmeter = @"";
            }
            if (userInfo.length == 0)
            {
                userInfo = @"";
            }
            //stimeIndex
            NSString * stimeIndex = [self getStimeIndex];
            
            [query appendFormat:@"SELECT %@,'%@','%@',%@,%@,%@,%@,'%@','%@','%@','%@','%@'      UNION ALL ",
             userid,
             content,
             [amsg valueForKey:KeyStime],
             [NSNumber numberWithInt:0],
             [NSNumber numberWithInt:msgType],
             [NSNumber numberWithBool:YES],
             [amsg valueForKey:KeyStatus],
             @"0",
             userInfo,
             dmeter,
             showContent,
             stimeIndex
             ];
        }
        
        //执行更新语句
        [query deleteCharactersInRange:NSMakeRange(query.length-12-1,12)];
        BOOL bl = [_dataBase executeUpdate:query];
        if (!bl)
        {
            NSLog(@"writeToTalkPeopleAll 更新对话表失败 database action error:%@",[[_dataBase lastError] description]);
        }
    }
}

//转发：更新对话表，从好友列表转发
-(void)writeToTalkPeopleAll:(NSDictionary *)amsg ToUserinfor:(NSDictionary *)userinfoDic
{
    if (![_dataBase goodConnection])
    {
        [_dataBase open];
    }
    
    //获取转发的人的个人资料
    NSString * useridList = [userinfoDic.allKeys componentsJoinedByString:@","];
    
    //先从对话表中删除这些人的记录
    NSString * deleteQuery = [NSString stringWithFormat:@"DELETE FROM %@ WHERE userid IN(%@)",TALKPEOPLES,useridList];
    
    BOOL bl = [_dataBase executeUpdate:deleteQuery];
    if (!bl)
    {
        NSLog(@"writeToTalkPeopleAll 删除对话表失败 database action error:%@",[[_dataBase lastError] description]);
    }
    else
    {
        NSString * content = VALUE(KeyContent, amsg);
        NSString * showContent = @"";
        
        content = [[CJSONSerializer serializer] serializeObject:content];
        content = [[content dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
        
        //消息类型
        NSInteger msgType = 0;
        
        if ([VALUE(KeyType, amsg) isKindOfClass:[NSNumber class]])
        {
            msgType = [VALUE(KeyType, amsg) integerValue];
        }
        else
        {
            NSArray *mapArr = typeArrDefine;
            
            msgType = [mapArr indexOfObject:VALUE(KeyType, amsg)];
        }
        
        //显示文本
        if (msgType == ChatCellTypeSpecialText)
        {
            showContent = VALUE(KeyShowContent, amsg);
            if (showContent!= nil )
            {
                showContent = [[CJSONSerializer serializer] serializeObject:showContent];
                showContent = [[showContent dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
            }
        }
        
        //插入对话表中数据
        NSMutableString * query =[NSMutableString stringWithFormat:@"INSERT INTO %@ (userid,content,stime,unreadnum,type,me,status,level,userinfor,dmeter,showcontent,stimeIndex)   ",TALKPEOPLES];
        for (NSString * userid in userinfoDic.allKeys)
        {
            NSDictionary * userInfoDictionary = [userinfoDic valueForKey:userid];
            
            //dmeter
            NSString * dmeter = [userInfoDictionary valueForKey:KeyDmeter];
            NSString * userInfo = [[CJSONSerializer serializer] serializeDictionary:userInfoDictionary];
            userInfo = [[userInfo dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
            
            if(dmeter.length == 0)
            {
                dmeter = @"";
            }
            if (userInfo.length == 0)
            {
                userInfo = @"";
            }
            
            //stimeIndex
            NSString * stimeIndex = [self getStimeIndex];
            
            [query appendFormat:@"SELECT %@,'%@','%@',%@,%@,%@,%@,'%@','%@','%@','%@','%@'      UNION ALL ",
             userid,
             content,
             [amsg valueForKey:KeyStime],
             [NSNumber numberWithInt:0],
             [NSNumber numberWithInt:msgType],
             [NSNumber numberWithBool:YES],
             [amsg valueForKey:KeyStatus],
             @"0",
             userInfo,
             dmeter,
             showContent,
             stimeIndex
             ];
        }
        
        //执行更新语句
        [query deleteCharactersInRange:NSMakeRange(query.length-12-1,12)];
        BOOL bl = [_dataBase executeUpdate:query];
        if (!bl)
        {
            NSLog(@"writeToTalkPeopleAll 更新对话表失败 database action error:%@",[[_dataBase lastError] description]);
        }
    }
}

//2013-8-13 13：00：00 addBy：Wang Xj
//长连接开启时用来检测屏蔽那些人的个人资料,level是需要屏蔽的用户(),一般为600
-(NSArray *)getUserID:(NSString *)level
{
    if (![_dataBase goodConnection])
    {
        [_dataBase open];
    }
    
    NSString * userIDQuery = [NSString stringWithFormat:@"SELECT userid FROM %@ WHERE userinfor IS NOT NULL ORDER BY stime DESC LIMIT 0,100",TALKPEOPLES];
    
    if (level != nil)
    {
        userIDQuery = [NSString stringWithFormat:@"SELECT userid FROM %@ WHERE userinfor IS NOT NULL AND level <> %@ ORDER BY stime DESC LIMIT 0,100",TALKPEOPLES,@"600"];
    }
    
    FMResultSet * rs = [_dataBase executeQuery:userIDQuery];
    
    NSMutableArray * userIDArray = [NSMutableArray arrayWithCapacity:100];
    
    while ([rs next])
    {
        NSString * userid = [rs stringForColumn:KeyFromUid];
        if ([userid integerValue]<1000)
        {
            continue;
        }
        [userIDArray addObject:[rs stringForColumn:KeyFromUid]];
    }
    
    return userIDArray;
}

//从对话表中获取个人资料
-(NSArray *)getPersonalDataOfUseridFromTalk:(NSArray *)_users
{
    NSMutableArray *userIDList = [NSMutableArray arrayWithArray:_users];
    
    NSString *allUserid = [_users componentsJoinedByString:@","];
    NSString *query = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE userid in(%@)",TALKPEOPLES,allUserid];
    FMResultSet *rs = [_dataBase executeQuery:query];
    
    while ([rs next])
    {
        NSDictionary *amsg = [NSDictionary dictionaryWithObjectsAndKeys:
                              [rs stringForColumn:KeyFromUid],                         KeyFromUid,
                              [rs stringForColumn:keyPersonalInfo],                    keyPersonalInfo,nil];
        
        NSData *temp = [NSData dataFromBase64String:[amsg valueForKey:keyPersonalInfo]];
        NSMutableDictionary *arr=[[NSMutableDictionary alloc]initWithDictionary:[[CJSONDeserializer deserializer] deserializeAsDictionary:temp error:nil]];
        [arr setValue:[amsg valueForKey:KeyFromUid] forKey:KeyFromUid];
        
        NSMutableDictionary *dic=[NSMutableDictionary dictionaryWithDictionary:amsg];
        [dic setValue:arr forKey:keyPersonalInfo];
        [arr release];
        
        NSInteger index = [userIDList indexOfObject:[amsg valueForKey:KeyFromUid]];
        
        [userIDList replaceObjectAtIndex:index withObject:dic];
        
    }
    return userIDList;
}

//获取姓名、id
-(NSDictionary *)getPnameArray:(NSArray *)userList
{
    NSMutableDictionary *dataList = [[[NSMutableDictionary alloc] initWithCapacity:10] autorelease];
    
    NSString *allUserid = [userList componentsJoinedByString:@","];
    NSString *query = [NSString stringWithFormat:@"SELECT userinfor,userid FROM %@ WHERE userid in(%@) AND userinfor IS NOT NULL ",TALKPEOPLES,allUserid];
    FMResultSet *rs = [_dataBase executeQuery:query];
    while ([rs next])
    {
        NSData *temp = [NSData dataFromBase64String:[rs stringForColumn:keyPersonalInfo]];
        
        if (temp.length<=10)
        {
            continue;
        }
        NSMutableDictionary *arr=[[NSMutableDictionary alloc]initWithDictionary:[[CJSONDeserializer deserializer] deserializeAsDictionary:temp error:nil]];
        [arr setValue:[rs stringForColumn:KeyFromUid] forKey:KeyFromUid];
        
        [dataList setValue:arr forKey:[arr valueForKey:KeyPname]];
        [arr release];
    }
    return dataList;
}

#pragma mark 打招呼的处理
//对话表创建系统用户：600
-(BOOL)initSystemUser:(NSString *)userid ByMsg:(NSDictionary *)amsg
{
    if(![_dataBase goodConnection])
        [_dataBase open];
    
    [self initSystemPerson:nil];
    
    
    //查看对话表中是否有…600号
    NSString *query1 = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE userid=%@",TALKPEOPLES,userid];
    FMResultSet *rs = [_dataBase executeQuery:query1];
    BOOL new = YES;
    while ([rs next])
    {
        new = NO;
    }
    
    //对话表中没有600号时
    if (new)
    {
        NSString * userinfo = @"";
        NSString * dmeter = @"12794公里";
        
        NSMutableDictionary * userInfoDic = [NSMutableDictionary dictionaryWithCapacity:10];
        
        [userInfoDic setValue:@"http://file.koochat.com/photo-user-face/sysface_sayhi.jpg" forKey:KeyUface];
        [userInfoDic setValue:@"12794公里" forKey:KeyDmeter];
        [userInfoDic setValue:@"m" forKey:KeyGender];
        [userInfoDic setValue:@"陌生人打招呼" forKey:KeyUname];
        [userInfoDic setValue:[NSNumber numberWithInt:12] forKey:KeyAge];
        
        userinfo = [[CJSONSerializer serializer] serializeDictionary:userInfoDic];
        userinfo = [[userinfo dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
        
        NSString *query = [NSString stringWithFormat:@"INSERT INTO %@ (userid,content,stime,unreadnum,type,ltime,me,status,level,userinfor,dmeter,showcontent,stimeIndex) VALUES ('%@',?,'%@',%@,%@,'%@',%@,%@,'%@','%@','%@',?,?)",TALKPEOPLES,userid,[amsg valueForKey:KeyStime],[amsg valueForKey:KeyUnreadNum],[amsg valueForKey:KeyType],[amsg valueForKey:KeyOnLinetime],[amsg valueForKey:KeyMe],[amsg valueForKey:KeyStatus],@"0",userinfo,dmeter];
        
        NSString * content = VALUE(KeyContent, amsg);
        
        content = [[CJSONSerializer serializer] serializeObject:content];
        content = [[content dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
        
        NSInteger msgType = 0;
        
        if ([VALUE(KeyType, amsg) isKindOfClass:[NSNumber class]])
        {
            msgType = [VALUE(KeyType, amsg) integerValue];
        }
        else
        {
            NSArray *mapArr = typeArrDefine;
            
            msgType = [mapArr indexOfObject:VALUE(KeyType, amsg)];
        }
        
        NSString * showContent = @"";
        if (msgType == ChatCellTypeSpecialText)
        {
            showContent = VALUE(KeyShowContent, amsg);
            if (showContent!= nil )
            {
                showContent = [[CJSONSerializer serializer] serializeObject:showContent];
                showContent = [[showContent dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
            }
        }
        
        //stimeIndex
        NSString * stimeIndex = [self getStimeIndex];
        
        BOOL bl = [_dataBase executeUpdate:query,content,showContent,stimeIndex];
        
        if (!bl)
        {
            NSLog(@"initSystemUser 更新失败 database action error:%@",[[_dataBase lastError] description]);
            return NO;
        }
        return new;
    }
    return new;
}

//更新打招呼（600号）的content、stime、type、unReadNum、me、status为最后一条打招呼的内容
-(void)updateLastDialogBySayHi:(NSDictionary *)amsg
{
    NSNumber * unReadNum = [[self getUnreadNumBySayHi:@"600"] valueForKey:KeyUnreadNum];
    
    NSString * content = VALUE(KeyContent, amsg);
    
    content = [[CJSONSerializer serializer] serializeObject:content];
    content = [[content dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    NSInteger msgType = 0;
    
    if ([VALUE(KeyType, amsg) isKindOfClass:[NSNumber class]])
    {
        msgType = [VALUE(KeyType, amsg) integerValue];
    }
    else
    {
        NSArray *mapArr = typeArrDefine;
        
        msgType = [mapArr indexOfObject:VALUE(KeyType, amsg)];
    }

    
    NSString * showContent = @"";
    if (msgType == ChatCellTypeSpecialText)
    {
        showContent = VALUE(KeyShowContent, amsg);
        if (showContent!= nil )
        {
            showContent = [[CJSONSerializer serializer] serializeObject:showContent];
            showContent = [[showContent dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
        }
    }
    
    //stimeIndex
    NSString * stimeIndex = [self getStimeIndex];
    
    NSString * dialogQuery = [NSString stringWithFormat:@"UPDATE %@ SET content='%@',stime='%@',type=%@,unReadNum=%@,me=%@,status=%@,showcontent='%@',stimeIndex = '%@' WHERE userid = 600",TALKPEOPLES,content,[amsg valueForKey:KeyStime],[NSNumber numberWithInt:[VALUE(KeyType, amsg) intValue]],unReadNum,[NSNumber numberWithInt:[VALUE(KeyMe, amsg) intValue]],[NSNumber numberWithInt:4],showContent,stimeIndex];
    
    BOOL bl = [_dataBase executeUpdate:dialogQuery];
    if (!bl)
    {
        NSLog(@"updateLastDialogBySayHi 更新失败 database action error:%@",[[_dataBase lastError] description]);
    }
}

-(NSString *)getLevelByUserID:(NSString *)userid
{
    if (![_dataBase goodConnection])
    {
        [_dataBase open];
    }
    NSString * query = [NSString stringWithFormat:@"SELECT level FROM %@ WHERE userid = %@",TALKPEOPLES,userid];
    
    FMResultSet * rs = [_dataBase executeQuery:query];
    NSString * level = nil;
    while ([rs next])
    {
        level = [rs stringForColumn:KeyLevel];
    }
    
    return level;
}

//更新未读消息
-(void)updateUnreadNum
{
    NSNumber * unReadNum = [[self getUnreadNumBySayHi:@"600"] valueForKey:KeyUnreadNum];
    NSString * dialogQuery = [NSString stringWithFormat:@"UPDATE %@ SET unReadNum=%@ WHERE userid = 600",TALKPEOPLES,unReadNum];
    
    BOOL bl = [_dataBase executeUpdate:dialogQuery];
    if (!bl)
    {
        NSLog(@"updateUnreadNum 更新失败 database action error:%@",[[_dataBase lastError] description]);
    }
}


//更新对话表中用户的level
-(void)updateDialogUserLevel:(NSString *)userid toLevel:(NSString *)level
{
    if(![_dataBase goodConnection])
        [_dataBase open];
    
    level = @"0";
    
    NSString * dialogQuery = [NSString stringWithFormat:@"UPDATE %@ SET level = %@ WHERE userid = %@",TALKPEOPLES,level,userid];
    
    BOOL bl = [_dataBase executeUpdate:dialogQuery];
    
    if (!bl)
    {
        NSLog(@"updateDialogUserLevel database action error:%@",[[_dataBase lastError] description]);
    }
}

//获取未读消息数量和打招呼的人的数量（一个是消息数量、一个是人的数量）
-(NSDictionary * )getUnreadNumBySayHi:(NSString *)userid
{
    NSNumber * value = [NSNumber numberWithInt:0];
    NSNumber * num = [NSNumber numberWithInt:0];
    
    NSString * UnReadNumQuery = [NSString stringWithFormat:@"SELECT SUM(unreadnum) AS _value,count(userid) AS _num FROM %@  WHERE level = %@ AND userinfor IS NOT NULL",TALKPEOPLES,userid];
    
    FMResultSet * rs = [_dataBase executeQuery:UnReadNumQuery];
    
    while ([rs next])
    {
        value = [NSNumber numberWithInt:[rs intForColumn:@"_value"]];
        num = [NSNumber numberWithInt:[rs intForColumn:@"_num"]];
    }
    
    return [NSDictionary dictionaryWithObjectsAndKeys:value,KeyUnreadNum,num,@"peopleCount", nil];
}


//检查用户本次消息是否是打招呼,是打招呼：返回YES；不是打招呼：返回NO
-(BOOL)checkDialogIsSayHi:(NSString *)userid
{
    //判断两人的关系；是好友就直接返回NO
    if ([self judgeRelationship:userid])
    {
        return NO;
    }
    
    NSString * query = [NSString stringWithFormat:@"SELECT COUNT(userid) AS _value FROM %@ WHERE userid = %@ AND level = %@",TALKPEOPLES,userid,@"0"];
    FMResultSet * rs1 = [_dataBase executeQuery:query];
    NSInteger num = 0;
    while ([rs1 next])
    {
        num = [rs1 intForColumn:@"_value"];
    }
    //如果在对话表中找到了该人，则说明不是打招呼了
    if (num)
    {
        return NO;
    }
    
    //不是好友，判断两人之间是否有交互（我发消息了，对方也发消息了）
    NSString * tableName = [self getTableNameForUid:userid];
    NSString * query1 = [NSString stringWithFormat:@"SELECT COUNT(userid) AS _value1 FROM %@ WHERE me = 1 AND userid = %@ ",tableName,userid];
    
    NSInteger num1 = 0;//me为1的有多少条
    
    FMResultSet * rs = [_dataBase executeQuery:query1];
    while ([rs next])
    {
        num1 = [rs intForColumn:@"_value1"];
    }
    
    //如果我有回复，则说明不是打招呼，没有回复说明是打招呼
    if (num1<=0)
    {
        if ([self isExistInTable:userid])
        {
            return NO;
        }
        return YES;
    }
    else
    {
        return NO;
    }
    
    return YES;
}

//已聊过天表
-(BOOL)initChatYetTable
{
    if(![_dataBase goodConnection])
        [_dataBase open];
    
    if(![_dataBase tableExists:TALKPEOPLESTABLE])
    {
        NSDictionary *queryDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                  DBFieldType_INTEGER, KeyID,
                                  DBFieldType_TEXT,    KeyFromUid,      //对话中对方的UserID
                                  nil];
        NSString *query = [NSString stringWithFormat:@"CREATE TABLE %@ (%@ , PRIMARY KEY(userid ASC))",TALKPEOPLESTABLE,[self getPar1StrFromDic:queryDic]];
        
        BOOL ff = [_dataBase executeUpdate:query];
        
        if(!ff)
        {
            NSLog(@"initChatYetTable database action error:%@",[[_dataBase lastError] description]);
            return NO;
        }
        else
        {
            return YES;
            NSLog(@"initChatYetTable 创建成功");
        }
    }
    return YES;
}

//将userid添加到已聊天表中（以后打招呼不显示在打招呼列表中）
-(void)insertChatTable:(NSString *)userID
{
    if (![_dataBase goodConnection])
    {
        [_dataBase open];
    }
    [self initChatYetTable];
    
    //检查以前是否与该用户聊过天
    NSString * InsertQuery = [NSString stringWithFormat:@"INSERT INTO %@(userid,ID) VALUES(%@,?)",TALKPEOPLESTABLE,userID];
    
    BOOL bl =  [_dataBase executeUpdate:InsertQuery,[NSNumber numberWithInt:1]];
    
    if (!bl)
    {
        NSLog(@"insertChatTable database action error:%@",[[_dataBase lastError] description]);
    }
}

//判断以前有没有聊过天；YES：聊过天，NO：没聊过
-(BOOL)isExistInTable:(NSString *)userID
{
    if (![_dataBase goodConnection])
    {
        [_dataBase open];
    }
    
    //检查以前是否与该用户聊过天
    NSString * SelectQuery = [NSString stringWithFormat:@"SELECT COUNT(userid) AS _value FROM %@ WHERE userid = %@",TALKPEOPLESTABLE,userID];
    
    FMResultSet * rs = [_dataBase executeQuery:SelectQuery];

    NSInteger count = 0;//默认没有聊过天
    
    while ([rs next])
    {
        count = [rs intForColumn:@"_value"];
    }
 
    if (count)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

//更新打招呼的未读消息条数
-(void)updateSayHiUnReadNum
{
    [self initSystemPerson:nil];
    NSNumber * unReadNum = [[self getUnreadNumBySayHi:@"600"] valueForKey:KeyUnreadNum];
    NSString * dialogQuery = [NSString stringWithFormat:@"UPDATE %@ SET unReadNum=%@ WHERE userid = 600",TALKPEOPLES,unReadNum];
    
    BOOL bl = [_dataBase executeUpdate:dialogQuery];
    if (!bl)
    {
        NSLog(@"updateSayHiUnReadNum 更新失败 database action error:%@",[[_dataBase lastError] description]);
    }
}

//清空所有二级目录；userid为二级目录的level值如：600
-(void)clearAllSecondaryUserMsg:(NSString *)userid andUserArray:(NSArray *)secondaryUser
{
    if(![_dataBase goodConnection])
        [_dataBase open];
    NSString * query = nil;
   
    query = [NSString stringWithFormat:@"DELETE FROM %@ WHERE level = %@",TALKPEOPLES,userid];
    
    BOOL bl = [_dataBase executeUpdate:query];
    
    if (!bl)
    {
        NSLog(@"clearAllSecondaryUserMsg 删除对话失败 database action error:%@",[[_dataBase lastError] description]);
        return;
    }
}

//更新打招呼（600号）的content、stime、type、unReadNum、me、status为最后一条打招呼的内容
-(void)setLastDialogBySayHi:(NSDictionary *)amsg
{
    NSNumber * unReadNum = [[self getUnreadNumBySayHi:@"600"] valueForKey:KeyUnreadNum];
    
    NSString * content = VALUE(KeyContent, amsg);
    
    if (content == nil || [content isEqualToString:@""])
    {
        return;
    }
    content = [[CJSONSerializer serializer] serializeObject:content];
    content = [[content dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    NSInteger msgType = 0;
    
    if ([VALUE(KeyType, amsg) isKindOfClass:[NSNumber class]])
    {
        msgType = [VALUE(KeyType, amsg) integerValue];
    }
    else
    {
        NSArray *mapArr = typeArrDefine;
        
        msgType = [mapArr indexOfObject:VALUE(KeyType, amsg)];
    }
    
    
    NSString * showContent = @"";
    if (msgType == ChatCellTypeSpecialText)
    {
        showContent = VALUE(KeyShowContent, amsg);
        if (showContent != nil)
        {
            showContent = [[CJSONSerializer serializer] serializeObject:showContent];
            showContent = [[showContent dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
        }
    }

    
    NSString * dialogQuery = [NSString stringWithFormat:@"UPDATE %@ SET content='%@',stime='%@',type=%@,unReadNum=%@,me=%@,status=%@,showcontent='%@' WHERE userid = 600",TALKPEOPLES,content,[amsg valueForKey:KeyStime],[NSNumber numberWithInt:[VALUE(KeyType, amsg) intValue]],unReadNum,[NSNumber numberWithInt:[VALUE(KeyMe, amsg) intValue]],showContent,[NSNumber numberWithInt:4]];
    
    BOOL bl = [_dataBase executeUpdate:dialogQuery];
    if (!bl)
    {
        NSLog(@"setLastDialogBySayHi 更新失败 database action error:%@",[[_dataBase lastError] description]);
    }
}

#pragma mark - 对话聊天记录表的初始化和写入聊天信息
//addBy：Wang Xj at 2013-7-3 13：55
//初始化十张聊天记录表，表名chat_myID_0(0~9)
-(BOOL)initDetailChatMessageTable
{
    if(![_dataBase goodConnection])
        [_dataBase open];
    
    NSString *tableName = @"";
    
    for(int i = 0; i < 10; i++)
    {
        tableName = [NSString stringWithFormat:@"chat_%@_%d",MyAppDataManager.useruid,i];
        
        if(![_dataBase tableExists:tableName])
        {
            NSDictionary *queryDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                      DBFieldType_TEXT,    KeyChatid,
                                      DBFieldType_INTEGER, KeyID,
                                      DBFieldType_TEXT,    KeyContent,
                                      DBFieldType_BOOL,    KeyMe,
                                      DBFieldType_INTEGER, KeyStatus,
                                      DBFieldType_INTEGER, KeyType,
                                      DBFieldType_INTEGER, KeyBubbleID,
                                      DBFieldType_INTEGER, KeyHeight,
                                      DBFieldType_TEXT,    KeyStime,
                                      DBFieldType_BOOL,    KeyShowtime,
                                      DBFieldType_INTEGER, KeyMediaStatus,
                                      DBFieldType_TEXT,    KeyShowFrom,
                                      DBFieldType_TEXT,    KeyFromUid,      //对话中对方的UserID
                                      DBFieldType_TEXT,    KeyMyUid,        //对话中自己的USerID
                                      DBFieldType_TEXT,    KeyDmeter,       //距离
                                      DBFieldType_TEXT,    KeyThumbnail,    //缩略图
                                      DBFieldType_TEXT,    KeyLinkTo,       //要跳转到的页面
                                      DBFieldType_TEXT,    KeyStimeIndex,   //搜索时的索引
                                      DBFieldType_INTEGER, KeyEffectiveTime,//搜索时的索引
                                      nil];
            NSString *query = [NSString stringWithFormat:@"CREATE TABLE %@ (%@ , PRIMARY KEY(chatid ASC))",tableName,[self getPar1StrFromDic:queryDic]];
            
            BOOL ff = [_dataBase executeUpdate:query];
            
            if(!ff)
            {
                NSLog(@"initDetailChatMessageTable database action error:%@",[[_dataBase lastError] description]);
                return NO;
            }
            else
            {
                NSLog(@"initDetailChatMessageTable 创建成功");
            }
        }
    }
    return YES;
}

//写入多条信息，传入的参数需要带有个人资料。 Wang Xj:插入聊天详情表聊天信息
-(NSInteger)writeToDialogDB:(NSDictionary *)people
{
    //先把自己发送给这个“people”消息状态设为已读（送达的改为已读）
    [self setStatusOfAll:@[ VALUE(KeyFromUid, people)]];
    
    //查看有没有新版聊天信息表
    [MyAppDataManager initDetailChatMessageTable];
    
    BOOL isSaveMsglist = NO;//默认不需要更新数据库（因为可能没有消息）
    //一次插入一个人的全部聊天记录
    NSDictionary *dataDic = [NSDictionary dictionaryWithDictionary:people];
    NSArray *dataArr = [NSArray arrayWithArray:[dataDic valueForKey:KeyMsglist]];
    NSString *tableName = [self getTableNameForUid:[people valueForKey:KeyFromUid]];
    
    NSMutableString *dialogsQuery = [NSMutableString stringWithFormat:@"INSERT INTO %@ (chatid,ID,content,me,status,type,bubbleID,height,stime,showtime,mediastatus,msgfrom,userid,myid,dmeter,thumbnail,linkto,stimeIndex,effectiveTime) ",tableName];
    
    //取距离
    NSString * dmeter = [self getDmeter:[people valueForKey:KeyFromUid]];
    
    if (dmeter == nil || [dmeter isEqualToString:@""])
    {
        dmeter = @"";
    }
    
    //时间显示
    NSString * selectShowTime =[NSString stringWithFormat: @"SELECT stime FROM %@ WHERE showtime = 1 AND userid = %@ ORDER BY stime DESC LIMIT 0,1",tableName,[people valueForKey:KeyFromUid]];
    
    FMResultSet * rs = [_dataBase executeQuery:selectShowTime];
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    self.lastShowwingTime = [formatter dateFromString:@"1900-01-01 00:00:00"];//初始化
    
    while ([rs next])
    {
        NSString * stime = [rs stringForColumn:KeyStime];
        self.lastShowwingTime = [formatter dateFromString:stime];
    }
    
    NSInteger effectiveMsgNum = 0;
    
    for (int i = 0; i < dataArr.count; i++)
    {
        NSDictionary *aChat = [NSDictionary dictionaryWithDictionary:[dataArr objectAtIndex:i]];
        
        //查看是否设置了不接收新用户注册通知、别人关注我的通知和别人查看了我的个人资料的通知，如果设置了，查看本消息是否为这三类。是就跳过本次循环
        if (![self checkIsReceiveSystemMessage:aChat])
        {
            continue;
        }
        
        //获取包装后的消息
//        NSLog(@"aChat:%@",aChat);
        aChat = [self getWholeMsg:aChat];
        
        /*
         insert into damo1 --damo1插入多行重复的记录
         select '张三','男',18 union all
         
         select '张三','男',18 union all
         
         select '张三','男',18 union all
         
         select '张三','男',18 union all
         
         select '张三','男',18 union all
         
         select '张三','男',18
         */
        //insert into select union all..select union all,插入多行，并且不去重
        [dialogsQuery appendFormat:@"SELECT '%@',%@,'%@',%@,%@,%@,%@,%@,'%@',%@,%@,'%@','%@','%@','%@','%@','%@','%@',%@      UNION ALL ",
         [aChat valueForKey:KeyChatid],
         [NSNumber numberWithInt:0],                //VALUE(KeyID, aChat),
         [aChat valueForKey:KeyContent],
         [NSNumber numberWithBool:NO],              //keyme ：别人发的是0；我发的是1
         [NSNumber numberWithInt:4],                //ChatStatus：ChatStatusNone
         [NSNumber numberWithInteger:[VALUE(KeyType, aChat) integerValue]],      //VALUE(KeyType, saysDic),
         [NSNumber numberWithInt:[VALUE(KeyBubbleID, aChat) integerValue]],
         [NSNumber numberWithInteger:[VALUE(KeyHeight, aChat) integerValue]],       //VALUE(KeyHeight, aChat),
         VALUE(KeyStime, aChat),
         [NSNumber numberWithBool:[VALUE(KeyShowtime, aChat) boolValue]],        //VALUE(KeyShowtime, aChat),
         [NSNumber numberWithInteger:[VALUE(KeyMediaStatus, aChat) integerValue]],  //VALUE(KeyMediaStatus, aChat),
         VALUE(KeyShowFrom, aChat),
         [people valueForKey:KeyFromUid],
         MyAppDataManager.useruid,
         dmeter,
         VALUE(KeyThumbnail, aChat),
         VALUE(KeyLinkTo, aChat),
         VALUE(KeyStimeIndex, aChat),
         VALUE(KeyEffectiveTime, aChat)
         ];
        effectiveMsgNum++;
        
        isSaveMsglist = YES;
    }
    
    self.lastShowwingTime = [formatter dateFromString:@"1900-01-01 00:00:00"];
    
//        NSLog(@"dialogsQuery1:%@",dialogsQuery);
    //去掉最后一个union all
    [dialogsQuery deleteCharactersInRange:NSMakeRange(dialogsQuery.length-12-1,12)];
    
//    NSLog(@"dialogsQuery2:%@",dialogsQuery);
    
    BOOL s1 = [_dataBase executeUpdate:dialogsQuery];
    
    if(!s1)
    {
        NSLog(@"插入聊天信息表：database action error:%@",[[_dataBase lastError] description]);
        
        NSString * ErrorLogPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]stringByAppendingPathComponent:@"errorLog.plist"];
        NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithContentsOfFile:ErrorLogPath];
        if (dic == nil)
        {
            dic = [NSMutableDictionary dictionary];
        }
        if([people valueForKey:KeyFromUid])
        {
            [dic setValue:[NSString stringWithFormat:@"%@",[[_dataBase lastError] description]] forKey:[NSString stringWithFormat:@"%@,%@",[people valueForKey:KeyFromUid],[people valueForKey:KeyFromUid]]];
            [dic setValue:dialogsQuery forKey:[people valueForKey:KeyFromUid]];
        }
        [dic writeToFile:ErrorLogPath atomically:YES];
    }
    [formatter release];
    return effectiveMsgNum;
}

//addBy:Wang Xj at 2013-7-3 16:00
//写入聊天记录表中聊天信息  （聊天界面使用）
-(void)writeToDetailChatTable:(NSDictionary *)aMsg andToUid:(NSString *)toUID
{
    //查看有没有新版聊天信息表
    [MyAppDataManager initDetailChatMessageTable];
    
    //1 判断聊天对方半圆号最后一位是0~9中的哪一个 以确定保存的表名
    NSString * tableName = [NSString stringWithFormat:@"chat_%@_%d",MyAppDataManager.useruid,[toUID intValue]%10];
    
    NSString * chatQuery = [NSString stringWithFormat:@"INSERT INTO %@ (chatid,ID,content,me,status,type,bubbleID,height,stime,showtime,mediastatus,msgfrom,userid,myid,dmeter,thumbnail,linkto,stimeIndex,effectiveTime) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",tableName];
    
    NSString * dmeter = [self getDmeter:toUID];
    
    NSString * selectShowTime =[NSString stringWithFormat: @"SELECT stime FROM %@ WHERE showtime = 1 AND userid = %@ ORDER BY stime DESC LIMIT 0,1",tableName,toUID];
    
    FMResultSet * rs = [_dataBase executeQuery:selectShowTime];
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    self.lastShowwingTime = [formatter dateFromString:@"1900-01-01 00:00:00"];
    
    while ([rs next])
    {
        NSString * stime = [rs stringForColumn:KeyStime];
        self.lastShowwingTime = [formatter dateFromString:stime];
    }
    
    NSDictionary *aChat = [NSDictionary dictionaryWithDictionary:aMsg];

    //获取包装后的消息
    NSLog(@"aChat前：%@",aChat);
    aChat = [self getWholeMsg:aChat];
    NSLog(@"aChat后：%@",aChat);
    //getWholeMsg方法中不文明用语的高度都没有加FromLabelHeight，但是自己发的不文明用语要显示提示，所以要加上FromLabelHeight,bw
    NSInteger height = [VALUE(KeyHeight, aChat) integerValue];
    if ([VALUE(KeyShowFrom, aChat) isEqualToString:@"bw"])
    {
        height += FromLabelHeight;
    }
    BOOL bl = [_dataBase executeUpdate:chatQuery,
               [aChat valueForKey:KeyChatid],
               [NSNumber numberWithInt:0],                //VALUE(KeyID, aChat),
               [aChat valueForKey:KeyContent],
               [NSNumber numberWithBool:YES],              //keyme ：别人发的是0；我发的是1
               [NSNumber numberWithInt:ChatStatusSending],                //ChatStatus：ChatStatusNone
               [NSNumber numberWithInteger:[VALUE(KeyType, aChat) integerValue]],      //VALUE(KeyType, saysDic),
               [NSNumber numberWithInt:[VALUE(KeyBubbleID, aChat) integerValue]],
               [NSNumber numberWithInteger:height],       //VALUE(KeyHeight, aChat),
               VALUE(KeyStime, aMsg),
               [NSNumber numberWithBool:[VALUE(KeyShowtime, aChat) boolValue]],        //VALUE(KeyShowtime, aChat),
               [NSNumber numberWithInteger:MediaStatusNormal],  //VALUE(KeyMediaStatus, aChat),
               VALUE(KeyShowFrom, aChat),
               toUID,
               MyAppDataManager.useruid,
               dmeter,
               VALUE(KeyThumbnail, aChat),
               VALUE(KeyLinkTo, aChat),
               VALUE(KeyStimeIndex, aChat),
               VALUE(KeyEffectiveTime, aChat)
               ];

    if(!bl)
    {
        NSLog(@"writeToDetailChatTable database action error:%@",[[_dataBase lastError] description]);
    }
    [formatter release];
}

#pragma mark - 包装新消息，包括消息的高度等数据
//本地化消息的时间、高度、内容等，并返回完整数据
-(NSDictionary *)getWholeMsg:(NSDictionary *)amsg
{
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    double timeInterval = 0;
    NSDate * stime = nil;
    
    //包装完整的数据
    NSMutableDictionary * wholeMsg = [NSMutableDictionary dictionaryWithCapacity:10];
    {
        NSDictionary *aChat = [NSDictionary dictionaryWithDictionary:amsg];
        NSDictionary *saysDic=[AppComManager getAMsgFrom64String:[aChat valueForKey:KeySays]];
        //处理消息，高度、来自、状态等等
        
        //新增提示信息类型、视频，如银行安全提示等
        NSArray *mapArr = typeArrDefine;
        
        NSInteger msgType = [mapArr indexOfObject:VALUE(KeyType, saysDic)];
        
        //如果消息类型超出了现有类型，默认为文本；
        if (msgType>8)
        {
            msgType = 0;
        }
        
        CGFloat height = 0 ;
        NSInteger mediaStatus = MediaStatusNormal;
        // 这里是搞时间的
        
        NSString * msgFrom = VALUE(KeyShowFrom, saysDic);
        
        if (msgFrom == nil || [msgFrom isEqualToString:@""])
        {
            msgFrom = @"mo";
        }
        
        BOOL showFrom=!([msgFrom isEqual:@"mo"]||([msgFrom isEqual:@"collect"]));//bw（不文明用语）、pb（破冰语）、ty（涂鸦）、mo（默认）、hints（提示）、specialApp（开放平台）、mg（魔法工具箱）、snap（阅后即焚）
        NSInteger effectiveTime = 0;//有效时间
        if ([msgFrom isEqualToString:@"hints"] || [msgFrom isEqualToString:@"bw"])
        {
            showFrom = NO;
        }
        else if ([msgFrom isEqualToString:@"snap"])//阅后即焚
        {
            effectiveTime = [VALUE(KeyEffectiveTime, saysDic) integerValue];
        }
        BOOL showTime = YES;
        
        //查看是否显示时间
        stime = [formatter dateFromString:[aChat valueForKey:KeyStime]];
        
        timeInterval = [self.lastShowwingTime timeIntervalSinceDate:stime];//stime大时，返回值为负
        
        if(fabs(timeInterval) > 90)
        {
            showTime = YES;
            self.lastShowwingTime = stime;
            
            if (msgType == CHatCellTYpeHints)//提示信息
            {
                showTime = NO;
            }
        }
        else
        {
            showTime = NO;
        }
        
        switch (msgType)
        {
            case ChatCellTypeText:
                if ([VALUE(KeyShowFrom, saysDic) isEqualToString:@"snap"] && ![amsg valueForKey:KeyMe])
                {
                    height = 84;
                }
                else
                {
                    height = [BanBu_SmileLabel heightForText:VALUE(KeyContent, saysDic)]+2*CellMarge+TimeLabelHeight;
                }
                break;
            case ChatCellTypeImage:
            {
                NSData * data = UIImageJPEGRepresentation([MyAppDataManager msgImageForImageUrlStr:VALUE(KeyContent, saysDic)], 1);
                
                if (data.length)
                {
                    height = [self setHeight:data]+2*CellMarge+TimeLabelHeight;
                }
                else
                {
                    height = ImageTypeHeight+2*CellMarge+TimeLabelHeight;
                }
            }
                break;
            case ChatCellTypeLocation:
                height = locationTypeHeight+2*CellMarge+TimeLabelHeight;
                break;
            case ChatCellTypeVoice:
            {
                height = VoiceTypeHeight +2*CellMarge+TimeLabelHeight;
            }
                break;
            case ChatCellTypeEmi:
                height = ImageTypeHeight+2*CellMarge+TimeLabelHeight;
                break;
            //2014年07月29日18:24:27，提示需要先加上时间，因为下面减去了时间的高度
            case CHatCellTYpeHints:
            {
                showTime = NO;//提示消息不显示时间
                BanBu_HintsViewCell * cell = [[BanBu_HintsViewCell alloc] init];
                cell.hintsLabel.text = VALUE(KeyContent, saysDic);
                height = [cell heightForTextHint:VALUE(KeyContent, saysDic)]+ 15 + TimeLabelHeight;
                [cell release];
            }
                break;
            case ChatCellTypeVideo:
                height = VideoTypeHeight+2*CellMarge+TimeLabelHeight;
                break;
            case ChatCellTypeFullScreenGif:
            {
                height = FullScreenTypeHeight+2*CellMarge+TimeLabelHeight;
            }
                break;
            case ChatCellTypeSpecialText:
            {
                NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithDictionary:aChat];

                if ([VALUE(KeyMe, dic) boolValue])
                {
                    height = 2*CellMarge+TimeLabelHeight;
                }
                else
                {
                    [dic setValue:[NSNumber numberWithBool:showTime] forKey:KeyShowtime];
                    [self performSelectorOnMainThread:@selector(getHeight:) withObject:dic waitUntilDone:YES];
                    height = 2*CellMarge+TimeLabelHeight;
                }
            }
                break;
            default:
                height = [BanBu_SmileLabel heightForText:[MyAppDataManager IsInternationalLanguage:VALUE(KeyContent, saysDic)]]+2*CellMarge+TimeLabelHeight;
                break;
        }
        
        height = height+(showFrom?18:0);
        
        if(msgType==ChatCellTypeVoice||msgType==ChatCellTypeImage || msgType == ChatCellTypeVideo || msgType == ChatCellTypeFullScreenGif)
        {
            height=height+(showFrom?8:0);
            
            NSString * filePath = [AppComManager pathForMsgMedia:VALUE(KeyContent, saysDic)];
            if ([FileManager fileExistsAtPath:filePath])
            {
                mediaStatus = MediaStatusNormal;
            }
            else
            {
                mediaStatus = MediaStatusDownload;//下载
            }
        }
        if(showTime)
        {
            if (msgType == CHatCellTYpeHints)//提示信息
            {
                showTime = NO;
                height -= TimeLabelHeight;
            }
        }
        else
        {
            height -= TimeLabelHeight;
        }
        
        NSString * content = VALUE(KeyContent, saysDic);
        
        if (content == nil || [content isEqualToString:@""])
        {
            [formatter release];
            return nil;
        }
//        content = [MyAppDataManager IsInternationalLanguage:content];
        content = [[CJSONSerializer serializer] serializeObject:content];
        content = [[content dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
        
        NSString * thumbnail = VALUE(KeyThumbnail, saysDic);
        if (thumbnail == nil || [thumbnail isEqualToString:@""])
        {
            thumbnail = @"";
        }
        else
        {
            thumbnail = [[CJSONSerializer serializer] serializeObject:thumbnail];
            thumbnail = [[thumbnail dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
        }
        
        NSString * linkto = VALUE(KeyLinkTo, saysDic);
        if (linkto == nil)
        {
            linkto = @"";
        }
        NSString * stime = [self getStime:aChat];
        
        NSString * chatID = [aChat valueForKey:KeyChatid];
        
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
        //创建搜索时的时间索引
        NSString * stimeIndex = [formatter stringFromDate:[NSDate date]];
        
        [wholeMsg setValue:chatID forKey:KeyChatid];
        [wholeMsg setValue:content forKey:KeyContent];
        [wholeMsg setValue:[NSNumber numberWithInt:msgType] forKey:KeyType];
        [wholeMsg setValue:[saysDic valueForKey:KeyBubbleID] forKey:KeyBubbleID];
        [wholeMsg setValue:[NSNumber numberWithInteger:height] forKey:KeyHeight];
        [wholeMsg setValue:stime forKey:KeyStime];
        [wholeMsg setValue:[NSNumber numberWithBool:showTime] forKey:KeyShowtime];
        [wholeMsg setValue:[NSNumber numberWithInt:mediaStatus] forKey:KeyMediaStatus];
        [wholeMsg setValue:msgFrom forKey:KeyShowFrom];
        [wholeMsg setValue:thumbnail forKey:KeyThumbnail];
        [wholeMsg setValue:linkto forKey:KeyLinkTo];
        [wholeMsg setValue:stimeIndex forKey:KeyStimeIndex];
        [wholeMsg setValue:[NSNumber numberWithInt:effectiveTime] forKey:KeyEffectiveTime];
    }
    [formatter release];
    return wholeMsg;
}

-(void)getHeight:(NSDictionary *)amsg
{
    NSLog(@"amsg:%@",amsg);
    NSDictionary *saysDic=[AppComManager getAMsgFrom64String:[amsg valueForKey:KeySays]];
    
    BanBu_SpecialText * web = [[BanBu_SpecialText alloc]init];
    
    [web setWebViewFrame:CGRectMake(0, 0, 180, 20)];
    web.alpha = 0;
    web.set = YES;
    web.cell = nil;
    web.showTime = [VALUE(KeyShowtime, amsg) boolValue];
    web.amsg = [NSDictionary dictionaryWithObjectsAndKeys:VALUE(KeyChatid, amsg),KeyChatid,VALUE(KeyFromUid, amsg),KeyFromUid, nil];
    web.userInteractionEnabled = NO;
    [web setContent:[MyAppDataManager IsInternationalLanguage:VALUE(KeyContent, saysDic)]];
    BanBu_AppDelegate * delegate =  (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
    [delegate.tabbarController.view addSubview:web];
//    [web release];
}

//重新设置specText的高度
-(void)setHeightSp:(NSDictionary *)amsg
{
    NSString * tableName = [self getTableNameForUid:VALUE(KeyFromUid, amsg)];
    NSString * query = [NSString stringWithFormat:@"UPDATE %@ SET height = ? WHERE chatid = ?",tableName];
    BOOL bl = [_dataBase executeUpdate:query,VALUE(KeyHeight, amsg),VALUE(KeyChatid, amsg)];
    if (!bl)
    {
        NSLog(@"setHeightSp:database action error:%@",[[_dataBase lastError]description]);
    }
    
    if (MyAppDataManager.appChatController && [MyAppDataManager.chatuid isEqualToString:VALUE(KeyFromUid, amsg)])
    {
        [self readTalkList:MyAppDataManager.chatuid WithNumber:MyAppDataManager.dialogs.count];
        [MyAppDataManager.appChatController.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
    }
}


-(BOOL)checkIsReceive:(NSDictionary *)people
{
    for (NSDictionary * amsg in [people valueForKey:KeyMsglist])
    {
        if (![self checkIsReceiveSystemMessage:amsg])
        {
            return NO;
        }
    }
    return YES;
}

//查看是否设置了接收新用户注册通知、别人关注我的通知和别人查看了我的个人资料的通知.如果设置为接收，返回YES;如果设置为不接收，返回NO
-(BOOL)checkIsReceiveSystemMessage:(NSDictionary *)amsg
{
    //查看消息类型是否为文本（text），不是文本时直接返回YES（说明不是这三类消息（__followyou__、__ihavevisityou__、__pleasetakecare__））；
    NSDictionary *saysDic=[AppComManager getAMsgFrom64String:[amsg valueForKey:KeySays]];
    if (![[saysDic valueForKey:KeyType] isEqualToString:@"text"])
    {
        return YES;
    }
    //查看消息内容为否为__followyou__、__followyou__、__pleasetakecare__
    else
    {
        //1查看本用户是否设置了接收这三类通知
        NSDictionary * settingsDic = [NSDictionary dictionaryWithDictionary:[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"settings"]];
        if ([[saysDic valueForKey:KeyContent] isEqualToString:@"__pleasetakecare__"])
        {
            //1.1新用户注册通知
            if (![[settingsDic valueForKey:@"takeCareNotification"] boolValue])
            {
                return NO;
            }
        }
        /*
        else if ([[saysDic valueForKey:KeyContent] isEqualToString:@"__ihavevisityou__"])
        {
            //1.2别人查看了我的个人资料
            if (![[settingsDic valueForKey:@"visitYouNotification"] boolValue])
            {
                MyAppDataManager.newRecord = YES;
                return NO;
            }
            else//设置接收来访记录，但是不存入数据库，在来访记录中显示
            {
                MyAppDataManager.newRecord = YES;
                return NO;
            }
        }
         */
        else if ([[saysDic valueForKey:KeyContent] isEqualToString:@"__followyou__"])
        {
            //1.3别人关注了我
            if (![[settingsDic valueForKey:@"followYouNotification"] boolValue])
            {
                return NO;
            }
        }
    }
    
    //如果都不是则返回YES，本消息可以接收
    return YES;
}
//判断自己是不是普通会员，是普通会员时，创建一个提示信息
-(BOOL)checkUserIsRegularMembers
{
    return NO;
}

//创建一个提示信息 根据传过来的chatID生成一个id
-(void)createHintsMsg:(NSDictionary *)aChat dmeter:(NSString *)dmeter
{
    {//该信息是提示信息，showtime为NO，height为固定，type为5，bubbleID为0，信息固定，msgFrom为“mo”
        NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        
        NSString *tableName = [self getTableNameForUid:[aChat valueForKey:KeyFromUid]];
        
        NSMutableString *dialogsQuery = [NSMutableString stringWithFormat:@"INSERT INTO %@ (chatid,ID,content,me,status,type,bubbleID,height,stime,showtime,mediastatus,msgfrom,userid,myid,dmeter) ",tableName];
        
        NSDictionary *saysDic=[AppComManager getAMsgFrom64String:[aChat valueForKey:KeySays]];
        //处理消息，高度、来自、状态等等
        
        //新增提示信息类型、视频，如银行安全提示等
        NSInteger msgType = 5;
        
        NSString * content = @"对方是高级会员，高级会员可以享受发送图片、语音、视频等消息，点击申请高级会员";
        
        CGFloat height = 0;
        BanBu_HintsViewCell * cell = [[BanBu_HintsViewCell alloc] init];
        cell.hintsLabel.text = VALUE(KeyContent, saysDic);
        height = [cell heightForTextHint:VALUE(KeyContent, saysDic)]+TimeLabelHeight+10;
        [cell release];

        
        NSInteger mediaStatus = MediaStatusNormal;
        // 这里是搞时间的
        
        NSString * msgFrom = @"mo";
        
        if(msgType==ChatCellTypeVoice||msgType==ChatCellTypeImage || msgType == ChatCellTypeVideo)
        {
            mediaStatus = MediaStatusDownload;//下载
        }
        
        BOOL showTime = NO;
        
        content = [[CJSONSerializer serializer] serializeObject:content];
        content = [[content dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
        
        NSString * stime = [self getStime:aChat];
        
        NSString * chatID = [aChat valueForKey:KeyChatid];
        
        stime = [NSString stringWithFormat:@"%@.1000",stime];
        chatID = [NSString stringWithFormat:@"%@.1000",chatID];
        
        [dialogsQuery appendFormat:@"SELECT '%@',%@,'%@',%@,%@,%@,%@,%@,'%@',%@,%@,'%@','%@','%@','%@'      UNION ALL ",
         chatID,
         [NSNumber numberWithInt:0],                //VALUE(KeyID, aChat),
         content,
         [NSNumber numberWithBool:NO],              //keyme ：别人发的是0；我发的是1
         [NSNumber numberWithInt:4],                //ChatStatus：ChatStatusNone
         [NSNumber numberWithInteger:msgType],      //VALUE(KeyType, saysDic),
         [NSNumber numberWithInt:[VALUE(KeyBubbleID, saysDic) integerValue]],
         [NSNumber numberWithInteger:height],       //VALUE(KeyHeight, aChat),
         stime,
         [NSNumber numberWithBool:showTime],        //VALUE(KeyShowtime, aChat),
         [NSNumber numberWithInteger:mediaStatus],  //VALUE(KeyMediaStatus, aChat),
         msgFrom,
         VALUE(KeyFromUid, aChat),
         MyAppDataManager.useruid,
         dmeter
         ];
        [_dataBase executeUpdate:dialogsQuery];
        [formatter release];
    }
}

//获取发送时间
-(NSString *)getStime:(NSDictionary *)aChat
{
    //先修改时间，将服务器时间与本地时间换算
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate * date = [formatter dateFromString:[aChat valueForKey:KeyStime]];
    
    //加上本地时间跟服务器的时间差
    date = [date dateByAddingTimeInterval:(-MyAppDataManager.timeDifference)];
    
    NSString * stime = [formatter stringFromDate:date];
    [formatter release];
    
    return stime;
}

//获取发送时间索引
-(NSString *)getStimeIndex
{
    //先修改时间，将服务器时间与本地时间换算
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
    
    //加上本地时间跟服务器的时间差
    NSString * stimeIndex = [formatter stringFromDate:[NSDate date]];
    [formatter release];
    
    return stimeIndex;
}



//单纯为了更改上传文件后，服务器返回的url。（只更新KeyContent）
-(void)setDialogOne:(NSDictionary *)aMsg andToUid:(NSString *)touid
{
    NSString *tableName = [self getTableNameForUid:touid];
    NSString *dialogsOneQuery = [NSString stringWithFormat:@"UPDATE %@ SET content=? WHERE chatid=?",tableName];
    
    NSString * content = VALUE(KeyContent, aMsg);
    
    if (!content)
    {
        return;
    }
    content = [[CJSONSerializer serializer] serializeObject:content];
    content = [[content dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    BOOL s1 = [_dataBase executeUpdate:dialogsOneQuery,
               content,
               [aMsg valueForKey:KeyChatid]
               ];
    if(!s1)
    {
        NSLog(@"setDialogOne database action error:%@",[[_dataBase lastError] description]);
    }
}

//单纯为了更改上传缩略图后，服务器返回的url。（只更新KeyThumbnail）
-(void)setThumbnailOne:(NSDictionary *)aMsg andToUid:(NSString *)touid
{
    NSString *tableName = [self getTableNameForUid:touid];
    NSString *dialogsOneQuery = [NSString stringWithFormat:@"UPDATE %@ SET thumbnail=? WHERE chatid=?",tableName];
    
    NSString * content = VALUE(KeyThumbnail, aMsg);
    
    if (!content)
    {
        return;
    }
    content = [[CJSONSerializer serializer] serializeObject:content];
    content = [[content dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    BOOL s1 = [_dataBase executeUpdate:dialogsOneQuery,
               content,
               [aMsg valueForKey:KeyChatid]
               ];
    if(!s1)
    {
        NSLog(@"setDialogOne database action error:%@",[[_dataBase lastError] description]);
    }
}


//更改一条消息的状态（发送中->送达（或者失败））
-(void)setStatusOfOne:(NSDictionary *)statuDic
{
    //更新对话列表的人和这条聊天记录
    NSInteger chatstatus = 0;
    if([[statuDic valueForKey:@"status"] isEqualToString:@"fail"])
    {
        chatstatus = ChatStatusSendFail;
    }
    else if([[statuDic valueForKey:@"status"] isEqualToString:@"s"])
    {//s:送达
        chatstatus = ChatStatusSent;
    }
    else if([[statuDic valueForKey:@"status"] isEqualToString:@"r"])
    {//r:已读
        chatstatus = ChatStatusReaded;
    }
    else if([[statuDic valueForKey:@"status"] isEqualToString:@"none"])
    {
        chatstatus = ChatStatusNone;
    }
    
    //ChatStatusSent= 2；
    NSString *tableName = [self getTableNameForUid:[statuDic valueForKey:@"touid"]];
    NSString *dialogsOneQuery = [NSString stringWithFormat:@"UPDATE %@ SET status=?,mediastatus=? WHERE chatid=?",tableName];
    
    BOOL s1 = [_dataBase executeUpdate:dialogsOneQuery,
               [NSNumber numberWithInteger:chatstatus],
               VALUE(KeyMediaStatus, statuDic),
               [statuDic valueForKey:KeyChatid]
               ];
    if(!s1)
    {
        NSLog(@"setStatusOfOne 更新一条聊天记录的状态失败database action error:%@",[[_dataBase lastError] description]);
    }
    
    NSString *selectContentQuery = [NSString stringWithFormat:@"SELECT stime FROM %@ WHERE chatid='%@'",tableName,[statuDic valueForKey:KeyChatid]];
    
    NSString * stime = nil;
    FMResultSet * rs = [_dataBase executeQuery:selectContentQuery];
    while ([rs next])
    {
        stime = [rs stringForColumn:KeyStime];
    }
    
    NSString *talkPeopleOneQuery = [NSString stringWithFormat:@"UPDATE %@ SET status=? WHERE (userid=?) AND stime = '%@'",TALKPEOPLES,stime];
    
    BOOL s = [_dataBase executeUpdate:talkPeopleOneQuery,
              [NSNumber numberWithInt:chatstatus],
              [statuDic valueForKey:@"touid"]
              ];
    if(!s)
    {
        NSLog(@"setStatusOfOne 更新对话列表的状态失败database action error:%@",[[_dataBase lastError] description]);
    }
}

//更改多条消息的状态（发送中->送达（或者失败））（转发）
-(void)setStatusOfAllBySend:(NSDictionary *)statuDic
{
    if (statuDic.count<=0)
    {
        return;
    }
    if(![_dataBase tableExists:TALKPEOPLES])
    {
        return;
    }
    
    //更新对话列表的人和这条聊天记录
    NSInteger chatstatus = 0;
    if([[statuDic valueForKey:@"status"] isEqualToString:@"fail"])
    {
        chatstatus = ChatStatusSendFail;
    }
    else if([[statuDic valueForKey:@"status"] isEqualToString:@"s"])
    {//s:送达
        chatstatus = ChatStatusSent;
    }
    else if([[statuDic valueForKey:@"status"] isEqualToString:@"r"])
    {//r:已读
        chatstatus = ChatStatusReaded;
    }
    else if([[statuDic valueForKey:@"status"] isEqualToString:@"none"])
    {
        chatstatus = ChatStatusNone;
    }
    
    NSArray * statusList =[[statuDic valueForKey:@"touid"] componentsSeparatedByString:@","];
    
    
    ;
    NSDictionary * chatidDic = nil;
    
    if ([[statuDic valueForKey:KeyChatid] isKindOfClass:[NSDictionary class]])//转发
    {
        chatidDic = [statuDic valueForKey:KeyChatid];
    }
    else if([[statuDic valueForKey:KeyChatid] isKindOfClass:[NSString class]])//单个发送（点对点聊天）
    {
        chatidDic = [NSDictionary dictionaryWithObjectsAndKeys:[statuDic valueForKey:KeyChatid],[statusList objectAtIndex:0],nil];
    }
    
    for (NSString * userID in statusList)
    {
        //更新聊天记录的状态,要先找出最后一条keyme = 0的
        NSString *tableName = [self getTableNameForUid:userID];
        if(![_dataBase tableExists:tableName])
        {
            continue;
        }
        
        NSString *query1 = [NSString stringWithFormat:@"UPDATE %@ SET status=? WHERE (me=1) AND (chatid=?);",tableName];
        NSString * chatid = [chatidDic valueForKey:userID];
        BOOL s1 = [_dataBase executeUpdate:query1,[NSNumber numberWithInteger:chatstatus],chatid];
        
        if(!s1)
        {
            NSLog(@"setStatusOfAllBySend database action error:%@",[[_dataBase lastError] description]);
        }
        
    }
    
    //修改对话表消息状态
    NSString *query = [NSString stringWithFormat:@"UPDATE %@ SET status=%d WHERE (userid IN (%@)) AND (status <> 3)",TALKPEOPLES,chatstatus,[statuDic valueForKey:@"touid"]];
    
    BOOL bl = [_dataBase executeUpdate:query];
    if (!bl)
    {
        
    }
}

//更改对话列表和聊天记录中的送达状态为已读
-(void)setStatusOfAll:(NSArray *)statusList
{
    if (statusList.count<=0)
    {
        return;
    }
    if(![_dataBase tableExists:TALKPEOPLES])
    {
        return;
    }
    
    NSString * userIDString = [statusList componentsJoinedByString:@","];
    
    NSString *query = [NSString stringWithFormat:@"UPDATE %@ SET status=3 WHERE (userid IN (%@)) AND (status <> 3)",TALKPEOPLES,userIDString];
    
    BOOL s = [_dataBase executeUpdate:query];
    
    if(!s)
    {
        NSLog(@"setStatusOfAll 更新对话列表的状态失败database action error:%@",[[_dataBase lastError] description]);
        
        NSString * ErrorLogPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]stringByAppendingPathComponent:@"errorLog.plist"];
        NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithContentsOfFile:ErrorLogPath];
        if (dic == nil)
        {
            dic = [NSMutableDictionary dictionary];
        }
        [dic setValue:[NSString stringWithFormat:@"%@",[[_dataBase lastError] description]] forKey:userIDString];
        [dic setValue:query forKey:[NSString stringWithFormat:@"%@,%@",userIDString,query]];
        
        [dic writeToFile:ErrorLogPath atomically:YES];
    }
    
    for (NSString * userID in statusList)
    {
        //更新聊天记录的状态,要先找出最后一条keyme = 0的
        NSString *tableName = [self getTableNameForUid:userID];
        
        NSString *query1 = [NSString stringWithFormat:@"UPDATE %@ SET status=3 WHERE (me=1) AND (status=1) AND (userid IN (?));",tableName];
        
        BOOL s1 = [_dataBase executeUpdate:query1,userID];
        
        if(!s1)
        {
            NSLog(@"setStatusOfAll database action error:%@",[[_dataBase lastError] description]);
        }
        else
        {
            query = [NSString stringWithFormat:@"DELETE FROM %@ WHERE userid = %@ AND me = 1 AND msgfrom = 'snap' AND status = 3",tableName,userID];
            s = [_dataBase executeUpdate:query];
            
            if (s)
            {
                //更新回去最后一条消息
                query = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE userid = %@  ORDER BY stimeIndex DESC limit 0,1",tableName,userID];
                
                NSArray * dialog = [self readMessageSql:query];
                if (dialog.count)
                {
                    NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithDictionary:[dialog objectAtIndex:0]];
                    [dic setValue:userID forKey:KeyFromUid];
                    if ([[dic valueForKey:KeyShowFrom] isEqualToString:@"snap"])
                    {
                        [dic setValue:NSLocalizedString(@"snapText", nil) forKey:KeyContent];
                    }
                    [self setTalkPeopleOneNOUnread:dic];
                }
            }
        }
    }
}

//写聊天记录表,更新聊天记录表中该消息的发送状态发“发送中”，查找对话表中该用户的最后一条信息是否为本次发送的信息，如果是则状态改为发送中
-(void)updateDialogStateByReSend:(NSDictionary *)statuDic
{
    //更新对话列表的人和这条聊天记录
    
    NSString *tableName = [self getTableNameForUid:[statuDic valueForKey:KeyFromUid]];
    NSString *dialogsOneQuery = [NSString stringWithFormat:@"UPDATE %@ SET status=%@ WHERE chatid = '%@' ",tableName,[NSNumber numberWithInteger:2],[statuDic valueForKey:KeyChatid]];
    
    BOOL s1 = [_dataBase executeUpdate:dialogsOneQuery];
    if(!s1)
    {
        NSLog(@"updateDialogStateByReSend 更新一条聊天记录的状态失败database action error:%@",[[_dataBase lastError] description]);
    }
    
    //更改对话表中该人最后一条记录的状态为发送中（该记录满足stime和userid两项，所以keyiD确定该记录的唯一性）
    NSString *talkPeopleOneQuery = [NSString stringWithFormat:@"UPDATE %@ SET status=%@ WHERE (userid = ?) AND me = 1",TALKPEOPLES,[NSNumber numberWithInt:2]];
    
    BOOL s = [_dataBase executeUpdate:talkPeopleOneQuery,
              [statuDic valueForKey:KeyFromUid]
              ];
    
    NSString * ss = [NSString stringWithFormat:@"select * from ? where (userid = ?)"];
    FMResultSet *rs3 = [_dataBase executeQuery:ss,TALKPEOPLES,[statuDic valueForKey:KeyFromUid]];
    
    while ([rs3 next])
    {
        NSLog(@"status diag:%d",[rs3 intForColumn:KeyStatus]);
    }
    
    if(!s)
    {
        NSLog(@"updateDialogStateByReSend 更新对话列表的状态失败database action error:%@",[[_dataBase lastError] description]);
    }
}

//设置消息为语音时的消息为已读状态
-(BOOL)setMediaStatusReaded:(NSString *)chatid userID:(NSString *)userid
{
    if(![_dataBase goodConnection])
        [_dataBase open];
    NSString *tableName = [self getTableNameForUid:userid];
    
    NSString *dialogsOneQuery = [NSString stringWithFormat:@"UPDATE %@ SET mediastatus=? WHERE chatid=?",tableName];
    
    BOOL s1 = [_dataBase executeUpdate:dialogsOneQuery,[NSNumber numberWithInteger:MediaStatusReaded],chatid];
    if(!s1)
    {
        NSLog(@"setMediaStatusReaded 更新一条聊天记录的状态失败database action error:%@",[[_dataBase lastError] description]);
        return NO;
    }
    return YES;
}

-(NSString *)getDmeter:(NSString *)userid
{
    if (![_dataBase goodConnection])
    {
        [_dataBase open];
    }
    
    NSString * query = [NSString stringWithFormat:@"SELECT userinfor FROM %@ WHERE userid = %@",PersonalDataList,userid];
    
    FMResultSet * rs = [_dataBase executeQuery:query];
    
    while ([rs next])
    {
        NSString * userInfo = [rs stringForColumn:keyPersonalInfo];
        NSData *temp = [NSData dataFromBase64String:userInfo];
        NSDictionary *arr=[[NSDictionary alloc]initWithDictionary:[[CJSONDeserializer deserializer] deserializeAsDictionary:temp error:nil]];
        
        NSString * dmeter = [arr valueForKey:KeyDmeter];
        [arr release];
        return dmeter;
    }
    return nil;
}

////获取最大的chatid，没有就默认生成一个
-(NSString *)searchMaxChatid:(NSString *)chatuid
{
    if(![_dataBase goodConnection])
        [_dataBase open];
    
    NSString *query = [NSString stringWithFormat:@"SELECT MAX(chatid) AS _value FROM %@",[MyAppDataManager getTableNameForUid:chatuid]];
    
    FMResultSet *rs = [_dataBase executeQuery:query];
    NSString * chatid = nil;
    
    while ([rs next])
    {
        if([[rs stringForColumn:@"_value"]length])
        {
            chatid =[NSString stringWithFormat:@"%@",[rs stringForColumn:@"_value"]];
            
            if([chatid rangeOfString:@"."].location == NSNotFound)
            {
                chatid = [chatid stringByAppendingString:@".1000"];
            }
            else
            {
                NSArray *arr = [NSArray arrayWithArray:[chatid componentsSeparatedByString:@"."]];
                chatid = [NSString stringWithFormat:@"%@.%d",[arr objectAtIndex:0],[[arr objectAtIndex:1] intValue]+1];
            }
        }
        else
        {
            //当聊天记录为空的时候，需要给指定一个chatid
            NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
            [formatter setLocale:[NSLocale currentLocale]];
            [formatter setLocale:[NSLocale currentLocale]];
            [formatter setDateFormat:@"yyMMdd-HHmmss-00000000"];
            chatid = [formatter stringFromDate:[NSDate date]];
        }
    }
    
    return chatid;
}

//将开放平台发送的消息的跳转保存到聊天详情表
-(void)updateDialogLinkTo:(NSString*)linkto toUserID:(NSString *)userid toChatID:(NSString *)chatid;
{
    if (linkto == nil || [linkto isEqualToString:@""])
    {
        return;
    }
    if (![_dataBase goodConnection])
    {
        [_dataBase open];
    }
    NSString * tableName = [self getTableNameForUid:userid];
    NSString * dialogQuery = [NSString stringWithFormat:@"UPDATE %@ SET linkto=? WHERE chatid = ?",tableName];
    
    BOOL bl = [_dataBase executeUpdate:dialogQuery,linkto,chatid];
    
    if (!bl)
    {
        NSLog(@"updateDialogLinkTo更新linkto失败: %@",[[_dataBase lastError] description]);
    }
}

#pragma mark - 删除聊天记录，删除人
//删除一个人及其聊天记录表 修改时间：2013-8-19：17：07：00
-(NSArray *)useridListQuery:(NSArray *)useridArray
{
    NSMutableString * table0 = [NSMutableString string];
    NSMutableString * table1 = [NSMutableString string];
    NSMutableString * table2 = [NSMutableString string];
    NSMutableString * table3 = [NSMutableString string];
    NSMutableString * table4 = [NSMutableString string];
    NSMutableString * table5 = [NSMutableString string];
    NSMutableString * table6 = [NSMutableString string];
    NSMutableString * table7 = [NSMutableString string];
    NSMutableString * table8 = [NSMutableString string];
    NSMutableString * table9 = [NSMutableString string];
    
    BOOL isString = YES;
    if ([[useridArray lastObject] isKindOfClass:[NSDictionary class]])
    {
        isString = NO;
    }
    else if ([[useridArray lastObject] isKindOfClass:[NSString class]])
    {
        isString = YES;
    }
    
    NSString * aUserid = @"";
    for (int i = 0;i<useridArray.count;i++)
    {
        if (isString)
        {
            aUserid = [useridArray objectAtIndex:i];
        }
        else
        {
            NSDictionary * amsg = [useridArray objectAtIndex:i];
            aUserid = [amsg valueForKey:KeyFromUid];
        }
        
        switch ([aUserid integerValue]%10)
        {
            case 0:
            {
                if (table0.length)
                {
                    [table0 appendString:@","];
                }
                [table0 appendString:aUserid];
            }
                break;
            case 1:
            {
                if (table1.length)
                {
                    [table1 appendString:@","];
                }
                [table1 appendString:aUserid];
            }
                break;
            case 2:
            {
                if (table2.length)
                {
                    [table2 appendString:@","];
                }
                [table2 appendString:aUserid];
            }
                break;
            case 3:
            {
                if (table3.length)
                {
                    [table3 appendString:@","];
                }
                [table3 appendString:aUserid];
            }
                break;
            case 4:
            {
                if (table4.length)
                {
                    [table4 appendString:@","];
                }
                [table4 appendString:aUserid];
            }
                break;
            case 5:
            {
                if (table5.length)
                {
                    [table5 appendString:@","];
                }
                [table5 appendString:aUserid];
            }
                break;
            case 6:
            {
                if (table6.length)
                {
                    [table6 appendString:@","];
                }
                [table6 appendString:aUserid];
            }
                break;
            case 7:
            {
                if (table7.length)
                {
                    [table7 appendString:@","];
                }
                [table7 appendString:aUserid];
            }
                break;
            case 8:
            {
                if (table8.length)
                {
                    [table8 appendString:@","];
                }
                [table8 appendString:aUserid];
            }
                break;
            case 9:
            {
                if (table9.length)
                {
                    [table9 appendString:@","];
                }
                [table9 appendString:aUserid];
            }
                break;
            default:
                break;
        }
    }
    
    NSArray * tableQueryArray = [NSArray arrayWithObjects:table0,table1,table2,table3,table4,table5,table6,table7,table8,table9,nil];
    
    return tableQueryArray;
}

//删除对话列表
-(void)deleteTalkPeople:(NSArray *)useridArray
{
    if(![_dataBase goodConnection])
        [_dataBase open];
    if (!useridArray.count)
    {
        return;
    }
    NSString *query = [NSString stringWithFormat:@"DELETE FROM %@ WHERE userid IN(%@)",TALKPEOPLES,[useridArray componentsJoinedByString:@","]];
    
    BOOL s = [_dataBase executeUpdate:query];
    
    if(!s)
    {
        NSLog(@"deleteTalkPeople database action error:%@",[[_dataBase lastError] description]);
    }

    if ([[NSString stringWithFormat:@",%@,",[useridArray componentsJoinedByString:@","]] rangeOfString:@",600,"].location != NSNotFound)
    {
        //清除打招呼（只删除对话列表）
        [self clearAllSecondaryUserMsg:@"600" andUserArray:MyAppDataManager.secondaryTalkPeople];
    }
}

//addBy：Wang Xj at 2013-7-4 13:52
//删除一个人所有的聊天记录，不删除该人（即在对话表中有该人的记录，在聊天记录表中没有该人的记录）
-(BOOL)deleteAllChattingRecordsOfOnePerson:(NSString *)userID
{
    if(![_dataBase goodConnection])
        [_dataBase open];
    
    NSString * tableName = [self getTableNameForUid:userID];
    NSString *query = [NSString stringWithFormat:@"DELETE FROM %@ WHERE userid=%@;",tableName,userID];
    
    if(![_dataBase tableExists:tableName])
    {
        return NO;
    }
    
    BOOL s = [_dataBase executeUpdate:query];
    if(!s)
    {
        return NO;
        NSLog(@"deleteAllChattingRecordsOfOnePerson database action error:%@",[[_dataBase lastError] description]);
    }
    return YES;
}

//addBy: Wang Xj at 2013-7-4 13：25
//删除一个人一条聊天记录
-(BOOL)deleteOneChattingRecordOfOnePerson:(NSDictionary *)amsg
{
    if(![_dataBase goodConnection])
        [_dataBase open];
    NSString * tableName = [self getTableNameForUid:VALUE(KeyFromUid, amsg)];
    
    if(![_dataBase tableExists:tableName])
    {
        [_dataBase close];
        return NO;
    }
    
    NSString *query = [NSString stringWithFormat:@"DELETE FROM %@ WHERE chatid=?",tableName];
    
    BOOL s = [_dataBase executeUpdate:query,VALUE(KeyChatid, amsg)];
    if(!s)
    {
        return NO;
        NSLog(@"deleteOneChattingRecordOfOnePerson 删除一条聊天记录database action error:%@",[[_dataBase lastError] description]);
    }
    return YES;
}

//阅后即焚消息在删除时，同时清除对话表的数据
-(void)deleteTalkRecordOfOnePerson:(NSDictionary *)amsg
{
    if(![_dataBase goodConnection])
        [_dataBase open];
    
    //更新回去最后一条消息
    NSString * tableName = [self getTableNameForUid:VALUE(KeyFromUid, amsg)];
    
    NSString * query = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE userid = %@  ORDER BY stimeIndex DESC limit 0,1",tableName,VALUE(KeyFromUid, amsg)];
    
    NSArray * dialog = [self readMessageSql:query];
    if (dialog.count)
    {
        NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithDictionary:[dialog objectAtIndex:0]];
        [dic setValue:VALUE(KeyFromUid, amsg) forKey:KeyFromUid];
        if ([[dic valueForKey:KeyShowFrom] isEqualToString:@"snap"])
        {
            [dic setValue:NSLocalizedString(@"snapText", nil) forKey:KeyContent];
        }
        
        //更新对话表最后一条消息时,全部更新
        [self setTalkPeopleOneNOUnread:dic];
    }
    else
    {
        //更新最后一条消息
        NSMutableDictionary * dialogDic = [NSMutableDictionary dictionaryWithDictionary:amsg];
        [dialogDic setValue:@"" forKey:KeyContent];
        [dialogDic setValue:[NSNumber numberWithInt:0] forKey:KeyType];
        [dialogDic setValue:[NSNumber numberWithInt:0] forKey:KeyStatus];
        
        //当没有最后一条消息时不更新stime和me，只清除content、type、status
        [self setTalkPeopleOneNOStime:dialogDic];
    }
}

//更新阅后即焚消息的有效时间
-(BOOL)setEffectiveTime:(NSDictionary *)amsg
{
    if(![_dataBase goodConnection])
        [_dataBase open];
    NSString * tableName = [self getTableNameForUid:VALUE(KeyFromUid, amsg)];
    
    NSString *query = [NSString stringWithFormat:@"UPDATE %@ SET EffectiveTime = %@ WHERE chatid = ?",tableName,VALUE(KeyEffectiveTime, amsg)];
    
    BOOL s = [_dataBase executeUpdate:query,VALUE(KeyChatid, amsg)];
    if(!s)
    {
        return NO;
        NSLog(@"deleteOneChattingRecordOfOnePerson 删除一条聊天记录database action error:%@",[[_dataBase lastError] description]);
    }
    return YES;
}


#pragma mark - 获取对话消息数据,界面显示

-(NSArray *)readMessageSql:(NSString *)sqlQuery
{
    if(![_dataBase goodConnection])
        [_dataBase open];
    
    FMResultSet *rs = [_dataBase executeQuery:sqlQuery];
    NSMutableArray *orialArr = [NSMutableArray array];
    
    while ([rs next])
    {
        NSData * data = [NSData dataFromBase64String:[rs stringForColumn:KeyContent]];
        NSString * content = [[CJSONDeserializer deserializer] deserialize:data error:nil];
        
        NSString * thumbnailContent = @"";
        if ([[NSNumber numberWithInteger:[rs intForColumn:KeyType]] intValue] == ChatCellTypeVideo || [[NSNumber numberWithInteger:[rs intForColumn:KeyType]] intValue] == ChatCellTypeFullScreenGif)
        {
            NSData * thumbnailData = [NSData dataFromBase64String:[rs stringForColumn:KeyThumbnail]];
            thumbnailContent = [[CJSONDeserializer deserializer] deserialize:thumbnailData error:nil];
        }
        
        NSString * linkto = @"";
        if ([[NSNumber numberWithInteger:[rs intForColumn:KeyType]] intValue] == ChatCellTypeSpecialText )
        {
            linkto = [rs stringForColumn:KeyLinkTo];
        }
        
        NSDictionary *amsg = [NSDictionary dictionaryWithObjectsAndKeys:
                              [rs stringForColumn:KeyChatid],                                   KeyChatid,
                              [MyAppDataManager IsInternationalLanguage:content],               KeyContent,
                              [MyAppDataManager IsInternationalLanguage:content],               @"backupsContent",
                              [NSNumber numberWithBool:[rs boolForColumn:KeyMe]],               KeyMe,
                              [NSNumber numberWithInteger:[rs intForColumn:KeyStatus]],         KeyStatus,
                              [NSNumber numberWithInteger:[rs intForColumn:KeyType]],           KeyType,
                              
                              [NSNumber numberWithInteger:[rs intForColumn:KeyHeight]],         KeyHeight,
                              [MyAppDataManager currentTime:[rs stringForColumn:KeyStime]],     KeyStime,
                              [NSNumber numberWithBool:[rs boolForColumn:KeyShowtime]],         KeyShowtime,
                              [NSNumber numberWithInteger:[rs intForColumn:KeyMediaStatus]],    KeyMediaStatus,
                              [NSNumber numberWithInteger:[rs intForColumn:KeyBubbleID]],       KeyBubbleID,
                              [rs stringForColumn:KeyShowFrom],                                 KeyShowFrom,
                              [rs stringForColumn:KeyDmeter],                                   KeyDmeter,
                              [MyAppDataManager IsInternationalLanguage:thumbnailContent],      KeyThumbnail,
                              [MyAppDataManager IsInternationalLanguage:linkto],                KeyLinkTo,
                              [NSNumber numberWithInt:[rs intForColumn:KeyEffectiveTime]],      KeyEffectiveTime,
                              
                              nil];
        [orialArr addObject:amsg];
    }
    return orialArr;
}

#pragma mark - 读取聊天列表
-(NSArray *)readTalkPeopleListSql:(NSString *)sqlQuery
{
    FMResultSet *rs = [_dataBase executeQuery:sqlQuery];
    NSMutableArray * talkPeopleArray = [NSMutableArray arrayWithCapacity:20];
    
    while ([rs next])
    {
        NSInteger type = [rs intForColumn:KeyType]; //对话信息类型：文本，图片，声音，位置,表情
        NSString *str1;
        
        //确认消息类型
        if(type == ChatCellTypeText)
        {
            NSData * data = [NSData dataFromBase64String:[rs stringForColumn:KeyContent]];
            NSString * content = [[CJSONDeserializer deserializer] deserialize:data error:nil];
            
            str1 = content;
        }
        else if (type == ChatCellTypeSpecialText && [rs stringForColumn:KeyShowContent] != nil && [[rs stringForColumn:KeyShowContent] length])
        {
            NSData * data = [NSData dataFromBase64String:[rs stringForColumn:KeyShowContent]];
            NSString * showContent = [[CJSONDeserializer deserializer] deserialize:data error:nil];

            str1 = showContent;
        }
        //2014年11月05日16:19:46 by yinlinlin 提示类型消息
        else if (type == CHatCellTYpeHints)
        {
            NSData * data = [NSData dataFromBase64String:[rs stringForColumn:KeyShowContent]];
            NSString * showContent = [[CJSONDeserializer deserializer] deserialize:data error:nil];
            
            str1 = showContent;
        }
        else
        {
            NSData * data = [NSData dataFromBase64String:[rs stringForColumn:KeyContent]];
            NSString * content = [[CJSONDeserializer deserializer] deserialize:data error:nil];
            
            if ([content isEqualToString:NSLocalizedString(@"emitionType", nil)])
            {
                str1 = content;
            }
            else
            {                
                NSArray *mapArr = contentArrDefine;
                
                if(![[rs stringForColumn:KeyLasttalk] isEqualToString:@""]&& [rs stringForColumn:KeyLasttalk])
                {
                    if (type>8)//如果消息类型超出现有类型，默认为文本
                    {
                        type = 0;
                    }
                    str1 = [NSString stringWithFormat:@"%@",[mapArr objectAtIndex:type]];
                }
                else
                {
                    str1=@"";
                }
            }
        }
        
        
        //获取个人资料
        NSDictionary *amsg = [NSDictionary dictionaryWithObjectsAndKeys:
                              [rs stringForColumn:keyPersonalInfo],                           keyPersonalInfo,nil];
        
        NSData *temp = [NSData dataFromBase64String:[amsg valueForKey:keyPersonalInfo]];
        NSDictionary * userInfoDic = [[NSDictionary alloc]initWithDictionary:[[CJSONDeserializer deserializer] deserializeAsDictionary:temp error:nil]];
        
        if (userInfoDic.count)
        {
            NSNumber * sex;
            if ([[userInfoDic valueForKey:KeyGender] isEqualToString:@"m"])
            {
                sex = [NSNumber numberWithInt:1];
            }
            else
            {
                sex = [NSNumber numberWithInt:0];
            }
            //存对话信息
            
            NSMutableDictionary * amsg1 = [NSMutableDictionary dictionaryWithCapacity:10];
            
            [amsg1 setValue:[rs stringForColumn:KeyFromUid] forKey:KeyFromUid];
            [amsg1 setValue:[MyAppDataManager IsInternationalLanguage:str1] forKey:KeyContent];
            [amsg1 setValue:[MyAppDataManager currentTime:[rs stringForColumn:KeyStime]] forKey:KeyStime];
            [amsg1 setValue:[NSNumber numberWithInteger:[rs intForColumn:KeyUnreadNum]] forKey:KeyUnreadNum];
            [amsg1 setValue:[rs stringForColumn:KeyMe] forKey:KeyMe];
            [amsg1 setValue:[rs stringForColumn:KeyStatus] forKey:KeyStatus];
            [amsg1 setValue:[rs stringForColumn:KeyType] forKey:KeyType];
            [amsg1 setValue:sex forKey:KeySex];
            [amsg1 setValue:[rs stringForColumn:KeyStimeIndex] forKey:KeyStimeIndex];
            
            [amsg1 addEntriesFromDictionary:userInfoDic];
            
            if ([[amsg1 valueForKey:KeyFromUid] isEqualToString:@"500"] && ([[amsg1 valueForKey:KeyUnreadNum] integerValue] != 0))
            {
                [talkPeopleArray insertObject:amsg1 atIndex:0];
            }
            else
            {
                [talkPeopleArray addObject:amsg1];
            }
            
        }
        [userInfoDic release];
    }
    
    return talkPeopleArray;
}

-(BOOL)readMoreTwentyMessage;
{
    NSString *tableName = [self getTableNameForUid:self.chatuid];
    int number=[_dialogs count];
    if(number == 0)
        return NO;
    
    NSString *query = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE userid = %@ ORDER BY stimeIndex DESC limit 0,%d;",tableName,self.chatuid,number+20];
    NSArray * msgArray = [self readMessageSql:query];
    if (!msgArray.count)
    {
        return NO;
    }
    
    if (msgArray.count)
    {
        [_dialogs removeAllObjects];
        [_dialogs addObjectsFromArray:[[msgArray reverseObjectEnumerator] allObjects]];
    }
    
    return YES;
}

//获取更多消息
-(NSArray *)readMoreMessage
{
    NSString *tableName = [self getTableNameForUid:self.chatuid];
    int number=[_dialogs count];
    if(number == 0)
        return NO;
    
    NSString *query = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE userid = %@ ORDER BY stimeIndex DESC limit 0,%d;",tableName,self.chatuid,number+20];
    NSArray * msgArray = [self readMessageSql:query];
    
    return msgArray;
}
#pragma mark - 获取对话信息及聊天记录
//获取对话信息及聊天记录
- (void)readTalkList:(NSString *)touid WithNumber:(NSInteger)num
{
    static int count = 0;
    count = 0;
    if(![_dataBase goodConnection])
        [_dataBase open];
    if(touid)
    {
        NSString *query = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE userid = %@ ORDER BY stimeIndex DESC limit 0,%d;",[self getTableNameForUid:touid],touid,num];
        
        NSArray *orialArr = [self readMessageSql:query];

        if (orialArr.count==0)
        {
            orialArr = [self readMessageSql:query];
        }
        
        [_dialogs removeAllObjects];
        [_dialogs addObjectsFromArray:[[orialArr reverseObjectEnumerator] allObjects]];
    }
    else
    {
        num = MyAppDataManager.totalLoadedPeopleNum;
        if (num < 20)
        {
            num = 20;
        }
        
        NSString * query = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE userinfor IS NOT NULL AND level = '0' ORDER BY stimeIndex DESC,stime DESC limit 0,%d ",TALKPEOPLES,num];

        //取到数据时再刷新对话界面列表
        NSArray * talkpeopleArray = [self readTalkPeopleListSql:query];
        
        if (talkpeopleArray.count)
        {
            [_talkPeoples removeAllObjects];
            
            [_talkPeoples addObjectsFromArray:talkpeopleArray];
        }
    }
}

//辅助获取对话信息及聊天记录
- (NSMutableArray *)readTalkListAfterSendImage:(NSString *)touid WithNumber:(NSInteger)num
{
    if(![_dataBase goodConnection])
        [_dataBase open];
    NSMutableArray * dialogsForDealImageArray = [NSMutableArray array];
    if(touid)
    {
        //是按stimeIndex进行降序排列,limit 0,1 是只取记录中的第一条.如想取前10条则 limit 0,10或limit 10
        //如想取第10至20条则 limit 10,20
        NSString *query = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE userid = %@ ORDER BY stimeIndex DESC limit 0,%d;",[self getTableNameForUid:touid],touid,num];
        
        //调用读消息的方法
        NSArray *orialArr = [self readMessageSql:query];
        
        if (orialArr.count)
        {
            [dialogsForDealImageArray addObjectsFromArray:[[orialArr reverseObjectEnumerator] allObjects]];
        }
    }
    else
    {
        if (num == 0)
        {
            num = 50;
        }
        
        NSString * query = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE userinfor IS NOT NULL AND level = '0' ORDER BY stimeIndex DESC,stime DESC limit %d,20 ",TALKPEOPLES,num];
        
        NSArray * talkpeopleArray = [self readTalkPeopleListSql:query];
        
        [dialogsForDealImageArray removeAllObjects];
        
        [dialogsForDealImageArray addObjectsFromArray:talkpeopleArray];
        
    }
    return dialogsForDealImageArray;
}

//获取userid下的用户，现在对话表分为两级，level：0或空为顶级，直接在对话中显示；400、600等为顶级，点击顶级以后进入二级页面显示二级的用户，如好友验证在600下面。系统通知在400下，系统警告在500下；
-(NSArray *)readTalkPeopleByUserID:(NSString *)userid
{
    NSString * query = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE userinfor IS NOT NULL AND level = %@ ORDER BY stimeIndex DESC,stime DESC",TALKPEOPLES,userid];
    
    NSArray * talkpeopleArray = [self readTalkPeopleListSql:query];
    
    if (talkpeopleArray.count)
    {
        [_secondaryTalkPeople removeAllObjects];
        
        [_secondaryTalkPeople addObjectsFromArray:talkpeopleArray];
    }
    
    if (_secondaryTalkPeople.count == 0 )
    {
        [self deleteBlackDialog:@"600"];//删除600号
    }
    
    return _secondaryTalkPeople;
}

//systemUserid:打招呼为600
-(NSDictionary *)getTheLastSayHiUserinfo:(NSString *)systemUserid
{
    if (![_dataBase goodConnection])
    {
        [_dataBase open];
    }
    
    NSString * amsgQuery = [NSString stringWithFormat:@"SELECT userid,content,stime,type,showcontent FROM %@ WHERE level = %@ ORDER BY stimeIndex DESC,stime DESC LIMIT 0,1",TALKPEOPLES,systemUserid];
    
    FMResultSet * rs = [_dataBase executeQuery:amsgQuery];
    
    while ([rs next])
    {
        NSString * userid = @"";
        NSString * content;
        NSString * stime;
        
        NSInteger type = [rs intForColumn:KeyType]; //对话信息类型：文本，图片，声音，位置,表情
        NSString *str1;
        
        //确认消息类型
        if(type == ChatCellTypeText)
        {
            NSData * data = [NSData dataFromBase64String:[rs stringForColumn:KeyContent]];
            NSString * content = [[CJSONDeserializer deserializer] deserialize:data error:nil];
            
            str1 = content;
        }
        else if (type == ChatCellTypeSpecialText && [rs stringForColumn:KeyShowContent] != nil)
        {
            NSData * data = [NSData dataFromBase64String:[rs stringForColumn:KeyShowContent]];
            NSString * showContent = [[CJSONDeserializer deserializer] deserialize:data error:nil];
            
            str1 = showContent;
        }
        else
        {
            NSArray *mapArr = contentArrDefine;
            
            if(![[rs stringForColumn:KeyLasttalk] isEqualToString:@""]&& [rs stringForColumn:KeyLasttalk])
            {
                if (type>8)//如果消息类型超出现有类型，默认为文本
                {
                    type = 0;
                }
                str1 = [NSString stringWithFormat:@"%@",[mapArr objectAtIndex:type]];
            }
            else
            {
                str1=@"";
            }
        }
        
        userid = [rs stringForColumn:KeyFromUid];
        stime = [rs stringForColumn:KeyStime];
        content = [MyAppDataManager IsInternationalLanguage:str1];
        [MyAppDataManager.lastSayHiUserInfoDic setValue:content forKey:KeyContent];
        [MyAppDataManager.lastSayHiUserInfoDic setValue:stime forKey:KeyStime];
        [MyAppDataManager.lastSayHiUserInfoDic setValue:userid forKey:KeyFromUid];
    }
    if (VALUE(KeyFromUid, _lastSayHiUserInfoDic))
    {
        NSArray * array = [self getPersonInfo:@[VALUE(KeyFromUid, _lastSayHiUserInfoDic)]];
        
        if (array.count)
        {
            NSDictionary * userInfoDic = [array objectAtIndex:0];
            [_lastSayHiUserInfoDic addEntriesFromDictionary:userInfoDic];
            NSNumber * sex;
            if ([[userInfoDic valueForKey:KeyGender] isEqualToString:@"m"])
            {
                sex = [NSNumber numberWithInt:1];
            }
            else
            {
                sex = [NSNumber numberWithInt:0];
            }
            [_lastSayHiUserInfoDic setValue:sex forKey:KeySex];
        }
    }
    
    return _lastSayHiUserInfoDic;
}

//当对话前不是好友，对话中添加成为好友后调用本方法修改最后一条消息的显示
-(NSDictionary *)getTheLastSayHiUser
{
    NSString * query = [NSString stringWithFormat:@"SELECT * FROM %@ ORDER BY stimeIndex DESC,stime desc limit 0,1",TALKPEOPLES];
    
    FMResultSet * rs = [_dataBase executeQuery:query];
    
    NSMutableDictionary * amsg = [NSMutableDictionary dictionaryWithCapacity:10];
    
    while ([rs next])
    {
        NSString * content = [rs stringForColumn:KeyContent];
        if (content != nil)
        {
            NSData * data = [NSData dataFromBase64String:[rs stringForColumn:KeyContent]];
            content = [[CJSONDeserializer deserializer] deserialize:data error:nil];
        }
        
        NSString * showContent = [rs stringForColumn:KeyShowContent];
        if (showContent !=nil)
        {
            NSData * data = [NSData dataFromBase64String:[rs stringForColumn:KeyShowContent]];
            showContent = [[CJSONDeserializer deserializer] deserialize:data error:nil];
        }
        
        [amsg setValue:[rs stringForColumn:KeyFromUid] forKey:KeyFromUid];
        [amsg setValue:[rs stringForColumn:KeyStime] forKey:KeyStime];
        [amsg setValue:content forKey:KeyContent];
        [amsg setValue:showContent forKey:KeyShowContent];
        [amsg setValue:[NSNumber numberWithInt:[rs intForColumn:KeyType]] forKey:KeyType];
        [amsg setValue:[NSNumber numberWithInt:[rs intForColumn:KeyMe]] forKey:KeyStatus];
    }
    return amsg;
}

/*********聊天数据处理**********/
#pragma mark - 发送消息
//发送已读信息的用户id
-(void)sendReadedStatus:(NSArray *)useridArray
{
    BOOL sendReadStatus = YES;
    if (![[[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"settings"] valueForKey:@"systemset_friendreadstatus"]boolValue])
    {
        //不发动消息已读状态（因为系统设置界面设置的为NO）
        sendReadStatus = NO;
        
        NSLog(@"不显示已读");
        return;
    }
    NSLog(@"显示已读");
    NSMutableArray * array = [NSMutableArray arrayWithArray:useridArray];
    if(array.count>100)
    {
        NSRange range = NSMakeRange(100, array.count -100);
        
        [array removeObjectsInRange:range];
    }
    
    NSMutableString * readed_uidlist = [NSMutableString string];
    for (NSString * userid in array)
    {
        if (sendReadStatus)
        {
            if ([self judgeRelationship:userid])
            {
                //如果是好友就不提交该好友，因为设置了好友不提交已读状态
                continue;
            }
        }
        if (readed_uidlist.length)
        {
            [readed_uidlist appendString:@","];
        }
        [readed_uidlist appendString:userid];
    }
    NSMutableDictionary * sendDic = [NSMutableDictionary dictionaryWithObject:readed_uidlist forKey:@"readed_uidlist"];
    
    [AppComManager getBanBuData:BanBu_readMessage_byuser par:sendDic delegate:self];
}

//对话发消息
-(void)sendMsg:(NSDictionary *)aMsg toUid:(NSString *)uid
{
    NSMutableDictionary *sendDic = [NSMutableDictionary dictionaryWithDictionary:aMsg];
    [sendDic setValue:uid forKey:@"touid_list"];
    [sendDic setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];

    [AppComManager getBanBuData:BanBu_SendMessage_To_Server_V2 par:sendDic delegate:self];
}

#pragma mark - 将接收到的消息写入到数据库
-(void)saveMsgListToDB:(NSArray *)messageArray
{
    for (NSDictionary * temp in messageArray)
    {
        //过滤用户资料
        if (![self checkUserInfo:temp])
        {
            continue;
        }
        //消息存入数据库中
        [self writeToDB:temp];
        
        //过滤系统通知
        if (![self checkIsReceive:temp])
        {
            continue;
        }
        
        //在“点对点”对话界面
        if(MyAppDataManager.appChatController)
        {

            //当前正在对话的用户发过来的消息
            if([self.chatuid isEqualToString:[temp valueForKey:KeyFromUid]])
            {
                //是打招呼：返回YES；不是打招呼：返回NO
                if ([self checkDialogIsSayHi:self.chatuid])
                {
                    [self setUnreadNumber:0 With:@"600"];
                }
                
                //要刷新点对点页面
                [self setUnreadNumber:0 With:[temp valueForKey:KeyFromUid]];
                //更新界面
                NSArray * amsgArray = [self readTalkListAfterSendImage:[temp valueForKey:KeyFromUid] WithNumber:[[temp valueForKey:KeyMsglist] count]];
                [MyAppDataManager.appChatController performSelectorOnMainThread:@selector(insertInToTable:) withObject:amsgArray waitUntilDone:YES];
                
                [MyAppDataManager sendReadedStatus:@[ self.chatuid ]];
            }
            //在与其他人聊天时，发出声音提醒
            else
            {
                [self showStatusMessage:temp];
                //更新返回按钮的气泡
                [MyAppDataManager.appChatController setBadgeValue:[NSString stringWithFormat:@"%d",[MyAppDataManager getBadgeValue]] withButtonIndex:1];
                [self createMusic];
            }
            
            if (MyAppDataManager.appChatController.returnBtTitle.length)
            {
                [MyAppDataManager.appChatController setBadgeValue:[NSString stringWithFormat:@"%d",[MyAppDataManager getBadgeValue]] withButtonIndex:1];
            }
        }
        else//在全局界面时，发出声音提醒
        {
            [self showStatusMessage:temp];
        }
    }
}

//显示提示信息
-(void)showStatusMessage:(NSDictionary *)temp
{
    BanBu_AppDelegate *appDelegate = (BanBu_AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSArray * msgList = [temp valueForKey:KeyMsglist];
    NSString * aChat = [msgList objectAtIndex:0];
    
    NSDictionary * saysDic = [AppComManager  getAMsgFrom64String:[aChat valueForKey:KeySays]];

    NSString * content = [self getContent:saysDic];
    
    if ([[saysDic valueForKey:KeyShowFrom]isEqualToString:@"snap"])
    {
        content = NSLocalizedString(@"snapText", nil);
    }
    if (appDelegate.tabbarController.statueBar.isExist)//存在自定义状态栏
    {
        if (!appDelegate.tabbarController.statueBar.isShow)//自定义状态栏没显示
        {
            [appDelegate.tabbarController.statueBar reShowStatus:content];
        }
        else//自定义状态栏已显示
        {
            [appDelegate.tabbarController.statueBar changeMessge:content];
        }
    }
    else//不存在自定义状态栏
    {
        [appDelegate.tabbarController.statueBar showStatusMessage:content];
    }
    appDelegate.tabbarController.statueBar.userid = [temp valueForKey:KeyFromUid];
}

//获取显示的内容（文本、多媒体、视频、图片、语音、表情等）
-(NSString *)getContent:(NSDictionary *)saysDic
{
    NSString *str1 = nil;
    
    NSArray *mapArr = typeArrDefine;
    
    NSInteger msgType = [mapArr indexOfObject:VALUE(KeyType, saysDic)];
    
    //确认消息类型
    if(msgType == ChatCellTypeText)
    {
        str1 = VALUE(KeyContent, saysDic);
    }
    else if (msgType == ChatCellTypeSpecialText)
    {
        str1 = VALUE(KeyShowContent, saysDic);
    }
    else
    {
        //@"magicGif",@"specialApp"
        NSArray *mapArr = contentArrDefine;
        
        if(![VALUE(KeyContent, saysDic) isEqualToString:@""]&& VALUE(KeyContent, saysDic))
        {
            if (msgType>8)//如果消息类型超出现有类型，默认为文本
            {
                msgType = 0;
            }
            str1 = [NSString stringWithFormat:@"%@",[mapArr objectAtIndex:msgType]];
        }
        else
        {
            str1=@"";
        }
    }
    
    return str1;
}

//刷新聊天界面
-(void)refreashChatView:(NSArray *)useridArray
{
    //在“点对点”对话界面
    if(MyAppDataManager.appChatController)
    {
        NSString * useridList = [NSString stringWithFormat:@",%@,",[useridArray componentsJoinedByString:@","]];
        if ([useridList rangeOfString:[NSString stringWithFormat:@",%@,",self.chatuid]].location != NSNotFound)
        {
            [self readTalkList:self.chatuid WithNumber:self.dialogs.count];
            //主线程去刷新界面
            [MyAppDataManager.appChatController.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
        }
    }
}

//显示金币数
-(void)showGoldView:(NSNumber *)number andView:(UIView *)_aview
{
    CGFloat time = 1.35;
    if([number integerValue] == 0)
    {
        return;
    }
    else if ([number integerValue]<0)
    {
        time = 0.8;
    }
    
    SCGIFImageView *goldView = [[SCGIFImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 320)];
    goldView.center = CGPointMake(_aview.center.x, _aview.center.y-60);
    
    goldView.gifFile = [[NSBundle mainBundle]pathForResource:[NSString stringWithFormat:@"get_score_%@",number] ofType:@"gif"];
    [_aview addSubview:goldView];
    [goldView release];
    [goldView performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:time];
}
#pragma mark - BanBuRequestDelegate

- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    //先更新数据库，再更新数据源，最后更新界面，应该都是这个套路吧
    // if([[MyAppDataManager.appChatController.profile valueForKey:KeyFromUid] isEqualToString:[resDic valueForKey:KeyUid]]) 它的作用就是：如果当前页面不是原来那个人了，就不需要更新数据源了和刷新当前界面。
    if(error)
    {
        if(![error.domain isEqualToString:BanBuDataformatError] && [[error.userInfo valueForKey:@"fc"] isEqualToString:BanBu_ReceiveMessage_From_Server_V4])
        {
            if([[error.userInfo valueForKey:@"fc"] isEqualToString:BanBu_SendMessage_To_Server_V2])//转发后处理返回参数
            {
                NSDictionary *statuDic =  [NSDictionary dictionaryWithObjectsAndKeys:@"fail",@"status",[error.userInfo valueForKey:@"touid"],@"touid",[resDic valueForKey:KeyChatid],KeyChatid,[NSNumber numberWithInteger:MediaStatusNormal],KeyMediaStatus, nil];
                
                //转发消息，touid是多个id
                [self setStatusOfAllBySend:statuDic];
                
                //判断这条消息，还是这个人的嘛（self.dialogs可能已改变）
                if(MyAppDataManager.appChatController && [[NSString stringWithFormat:@",%@,",[error.userInfo valueForKey:KeyUid]] rangeOfString:[NSString stringWithFormat:@",%@,",MyAppDataManager.chatuid]].location != NSNotFound)
                {
                    NSString * chatid = @"";
                    
                    if ([[resDic valueForKey:KeyChatid]isKindOfClass:[NSDictionary class]])
                    {
                        chatid = [[resDic valueForKey:KeyChatid] valueForKey:MyAppDataManager.chatuid];
                    }
                    else if ([[resDic valueForKey:KeyChatid]isKindOfClass:[NSString class]])
                    {
                        chatid = [resDic valueForKey:KeyChatid];
                    }
                    
                    NSInteger row = [[MyAppDataManager.cellRowMapDic valueForKey:chatid] integerValue];
                    NSMutableDictionary *amsg = [NSMutableDictionary dictionaryWithDictionary:[self.dialogs objectAtIndex:row]];
                    [amsg setValue:[NSNumber numberWithInteger:ChatStatusSent] forKey:KeyStatus];
                    [amsg setValue:[NSNumber numberWithInteger:MediaStatusNormal] forKey:KeyMediaStatus];
                    [self.dialogs replaceObjectAtIndex:row withObject:amsg];
                    [MyAppDataManager.appChatController.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
                }
                else
                {
                    [MyAppDataManager readTalkList:nil WithNumber:0];
                }
            }
            [AppComManager startReceiveMsgFromUid:nil forDelegate:MyAppDataManager];
        }
        else if([[error.userInfo valueForKey:@"fc"] isEqualToString:BanBu_ReceiveMessage_From_Server_V4])
        {
            [AppComManager startReceiveMsgFromUid:nil forDelegate:MyAppDataManager];
        }
        return;
    }
    
    if([[resDic valueForKey:@"ok"] boolValue])
    {
        // 接收个人 对 个人的聊天 (已作废个人对个人的 2013-7-9 08：36)
        // 从服务器获取全部的数据
        if ([AppComManager respondsDic:resDic isFunctionData:BanBu_ReceiveMessage_From_Server_V4])//接消息
        {
            if([[resDic valueForKey:@"resultlist"]isKindOfClass:[NSArray class]] && [[resDic valueForKey:@"resultlist"]count])
            {
                if([[resDic valueForKey:@"servertime"] length])
                {
                    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                    
                    MyAppDataManager.timeDifference = [[formatter dateFromString:[NSString stringWithFormat:@"%@",[resDic valueForKey:@"servertime"]]] timeIntervalSinceNow];
//                    NSLog(@"MyAppDataManager.timeDifference:%g",MyAppDataManager.timeDifference);
                    [UserDefaults setObject:[NSNumber numberWithDouble:MyAppDataManager.timeDifference] forKey:@"timedifference"];
                    
                    [formatter release];
                }
                else
                {
                    MyAppDataManager.timeDifference = [[UserDefaults valueForKey:@"timedifference"] doubleValue];
                }
                
                MyAppDataManager.serverTime = [resDic valueForKey:@"servertime"];
                
                NSArray * resultArray = [NSArray arrayWithArray:[resDic valueForKey:@"resultlist"]];
                
                BOOL refresh = NO;
                BOOL record = NO;
                for (NSDictionary * resultDictionary in resultArray)
                {
                    if ([[resultDictionary valueForKey:@"fc"]isEqual:@"get_readstatus_byuidlist"])//消息的状态
                    {
                        //更改对话列表的已读未读的状态
                        [self setStatusOfAll:[resultDictionary valueForKey:@"list"]];
                        [self refreashChatView:[resultDictionary valueForKey:@"list"]];
                    }
                    else if ([[resultDictionary valueForKey:@"fc"]isEqual:@"get_message_ofmy"])//接收消息
                    {
                        //messageArray 存储消息列表中所有元素,包含个人信息、对话信息
                        NSArray * messageArray = [NSArray arrayWithArray:[resultDictionary valueForKey:@"list"]];
                        //调刘杨的接口存储id，有可能这里没有个人资料，所以要先判断是否为空
                        if (messageArray.count)
                        {
                            [self writePersonalDataToDB:messageArray];
                        }
                        
                        if ([[messageArray lastObject] valueForKey:@"msglist"])//没消息时不执行
                        {
                            [self saveMsgListToDB:messageArray];
                        }
                        refresh = YES;
                    }
                    else if([[resultDictionary valueForKey:@"fc"]isEqual:@"get_onlineinfor_byuidlist"])//取用户状态信息
                    {
//                        [self updateLastOnlineTimeAndDistanceOfPersonalDB:[resultDictionary valueForKey:@"list"]];
                    }
                    else if ([[resultDictionary valueForKey:@"fc"]isEqualToString:@"have_user_view_me"])
                    {
                        record = YES;
                        NSDictionary * settingsDic = [NSDictionary dictionaryWithDictionary:[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"settings"]];
                        //有来访记录
                        if (![[settingsDic valueForKey:@"visitYouNotification"] boolValue])
                        {
                            MyAppDataManager.newRecord = NO;
                        }
                        else//设置接收来访记录，但是不存入数据库，在来访记录中显示
                        {
                            MyAppDataManager.newRecord = YES;
//                            refresh = YES;
                        }
                    }
                    else if ([[resultDictionary valueForKey:@"fc"]isEqual:@"get_friendaction_ofmy"])//取“好友动态”气泡
                    {
                        [MyAppDataManager.unReadBroadInfor removeAllObjects];
                        
                        NSMutableDictionary *coutDic = [NSMutableDictionary dictionaryWithDictionary:[resultDictionary valueForKey:@"countof"]];
                        NSString *haoStr = [UserDefaults valueForKey:KeyLastSeeFriendDynamicTime];
                        NSString *moStr  = [UserDefaults valueForKey:KeyLastSeeMoDynamicTime];
                        NSString *fromtime_hao = [resultDictionary valueForKey:@"fromtime_hao"];
                        NSString *fromtime_mo  = [resultDictionary valueForKey:@"fromtime_mo"];
                        
                        if(haoStr.length)
                        {
                            if(![fromtime_hao isEqualToString:haoStr])
                            {
                                [coutDic setValue:@"0" forKey:@"h"];
                                [coutDic setValue:@"0" forKey:@"g"];
                            }
                        }
                        
                        if(moStr.length)
                        {
                            if([fromtime_mo isEqualToString:moStr])
                            {
                                [coutDic setValue:@"0" forKey:@"z"];
                            }
                        }
                        
                        [MyAppDataManager.unReadBroadInfor addEntriesFromDictionary:coutDic];
                        //取好友气泡（陌生人、关注、好友）并保存
                        [[NSNotificationCenter defaultCenter]postNotificationName:@"setFriendActionNum" object:nil];
                        
                        //写入数据库
                        [MyAppDataManager modifyUserBaseDataWithKey:KeyUnReadDynamicNum andData:MyAppDataManager.unReadBroadInfor];
                        
                        BanBu_AppDelegate *ap = (BanBu_AppDelegate *)[UIApplication sharedApplication].delegate;
                        NSInteger unReadNum = [[coutDic valueForKey:@"g"] integerValue]+[[coutDic valueForKey:@"h"] integerValue]+[[coutDic valueForKey:@"z"] integerValue];
                        BOOL i = unReadNum >0;
                        [ap.tabbarController.tabBar setTabBarNoticeView:i withButtonIndex:1];
                        
                        //用户在线通知：
                        //friendonline,followonline，附近人
                        NSMutableDictionary * parDic = [NSMutableDictionary dictionaryWithCapacity:2];
                        
                        if ([[resultDictionary valueForKey:@"friendonline"] isEqualToString:@"y"])
                        {
                            //好友在线
                            [parDic setValue:@"y" forKey:@"friendonline"];
                        }
                        else
                        {
                            //好友不在线
                            [parDic setValue:@"n" forKey:@"friendonline"];
                        }
                        
                        if ([[resultDictionary valueForKey:@"followonline"] isEqualToString:@"y"])
                        {
                            //关注在线
                            [parDic setValue:@"y" forKey:@"followonline"];
                        }
                        else
                        {
                            //关注不在线
                            [parDic setValue:@"n" forKey:@"followonline"];
                        }
                        
                        [[NSNotificationCenter defaultCenter]postNotificationName:@"friendOnline" object:parDic];
                    }
                    else if ([[resultDictionary valueForKey:@"fc"] isEqualToString:@"new_friend_coming"])
                    {
                        NSMutableDictionary *uidDic = [NSMutableDictionary dictionaryWithDictionary:[UserDefaults valueForKey:MyAppDataManager.useruid]];
                        
                        NSMutableDictionary * relationDic = [NSMutableDictionary dictionaryWithDictionary:[uidDic valueForKey:FriendShip]];
                        NSString * friendStr = [relationDic valueForKey:@"h"];
                        NSString * addUid = [resultDictionary valueForKey:@"list"];
                        
                        if ([friendStr rangeOfString:[NSString stringWithFormat:@",%@,",addUid]].location != NSNotFound)
                        {
                            return;
                        }
                        
                        NSString * friendListStr =[NSString stringWithFormat:@"%@,%@",addUid,friendStr];
                        
                        [relationDic setValue:friendListStr forKeyPath:@"h"];
                        [uidDic setValue:relationDic forKeyPath:FriendShip];
                        
                        [UserDefaults setValue:uidDic forKey:MyAppDataManager.useruid];
                        [UserDefaults synchronize];
                    }
                }
                
                if (refresh)
                {
                    if (MyAppDataManager.secondaryDialog)
                    {
                        [self createMusic];
                        //更新二级界面
                        [_secondaryDialog performSelectorOnMainThread:@selector(updateBadgeShow) withObject:nil waitUntilDone:YES];
                    }
                    else if (!MyAppDataManager.appChatController)
                    {
                        if (!record)
                        {
                            [self createMusic];
                        }
                        
                        BanBu_AppDelegate *appDelegate = (BanBu_AppDelegate *)[[UIApplication sharedApplication] delegate];
                        if (appDelegate.tabbarController.selectedIndex == 2)
                        {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [appDelegate updateBadge];
                            });
                        }
                        else
                        {
                            NSString * unReadNum = [NSString stringWithFormat:@"%d",[MyAppDataManager getBadgeValue]];
                            
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [appDelegate.tabbarController.tabBar setBadgeValue:unReadNum withButtonIndex:2];
                            });
                        }
                    }
                }
            }
            
            //在全局界面时
            if(!MyAppDataManager.appChatController)
            {
                [AppComManager startReceiveMsgFromUid:nil forDelegate:MyAppDataManager];
            }
        }
        else if([AppComManager respondsDic:resDic isFunctionData:BanBu_SendMessage_To_Server_V2])//发送后处理返回参数
        {
            if (MyAppDataManager.friendController)
            {
                [MyAppDataManager.friendController performSelectorOnMainThread:@selector(dismissTKLoading) withObject:nil waitUntilDone:YES];
            }
            else if(MyAppDataManager.transmitController)
            {
                [MyAppDataManager.transmitController performSelectorOnMainThread:@selector(dismissTKLoading) withObject:nil waitUntilDone:YES];
            }
            
            NSDictionary *statuDic =  [NSDictionary dictionaryWithObjectsAndKeys:@"s",@"status",[resDic valueForKey:@"touid"],@"touid",[resDic valueForKey:KeyChatid],KeyChatid,[NSNumber numberWithInteger:MediaStatusNormal],KeyMediaStatus, nil];
            
            //转发消息，touid是多个id
            [self setStatusOfAllBySend:statuDic];
            
            //判断这条消息，还是这个人的嘛（self.dialogs可能已改变）
            if(MyAppDataManager.appChatController && [[NSString stringWithFormat:@",%@,",[resDic valueForKey:KeyUid]] rangeOfString:[NSString stringWithFormat:@",%@,",MyAppDataManager.chatuid]].location != NSNotFound)
            {
                NSString * chatid = @"";
                
                if ([[resDic valueForKey:KeyChatid]isKindOfClass:[NSDictionary class]])
                {
                    chatid = [[resDic valueForKey:KeyChatid] valueForKey:MyAppDataManager.chatuid];
                }
                else if ([[resDic valueForKey:KeyChatid]isKindOfClass:[NSString class]])
                {
                    chatid = [resDic valueForKey:KeyChatid];
                }
                
                NSInteger row = [[MyAppDataManager.cellRowMapDic valueForKey:chatid] integerValue];
                if (row> self.dialogs.count-1)
                {
                    return;
                }
                NSMutableDictionary *amsg = [NSMutableDictionary dictionaryWithDictionary:[self.dialogs objectAtIndex:row]];
                [amsg setValue:[NSNumber numberWithInteger:ChatStatusSent] forKey:KeyStatus];
                [amsg setValue:[NSNumber numberWithInteger:MediaStatusNormal] forKey:KeyMediaStatus];
                [self.dialogs replaceObjectAtIndex:row withObject:amsg];
                [MyAppDataManager.appChatController.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
                if ([[resDic valueForKey:@"getscore"] integerValue])
                {
                    NSNumber * number = [NSNumber numberWithInt:[[resDic valueForKey:@"getscore"] integerValue]];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self showGoldView:number andView:MyAppDataManager.appChatController.navigationController.view];

                    });
                }
            }
            else
            {
                [MyAppDataManager readTalkList:nil WithNumber:0];
            }
        }
        else if([AppComManager respondsDic:resDic isFunctionData:BanBu_Set_User_View])
        {
            if([resDic valueForKey:@"ok"])
            {
                [MyAppDataManager.peopleReaded removeAllObjects];
            }
            [UserDefaults setValue:MyAppDataManager.peopleReaded forKey:@"peopleReaded"];
        }
        //处理发送到服务器的已读消息的用户列表后返回成功的
        else if([AppComManager respondsDic:resDic isFunctionData:BanBu_readMessage_byuser])
        {
            NSLog(@"发送已读消息状态用户id返回成功");
        }
        else if([AppComManager respondsDic:resDic isFunctionData:Banbu_Send_Feedback])
        {
            NSLog(@"个人资料：%@",resDic);
        }
        else if([AppComManager respondsDic:resDic isFunctionData:BanBu_GetFriendList_transmit])
        {
            //获取好友列表，转发信息时用
            NSString * fileName = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"friendList_Transmit"];
            
            NSArray * friendListArray = [resDic valueForKey:@"list"];
            
            NSDictionary * dictionary = [NSDictionary dictionaryWithObjectsAndKeys:[NSDate date],@"updateDate",friendListArray,FriendShip, nil];
            
            //归档
            [NSKeyedArchiver archiveRootObject:dictionary toFile:fileName];
            
            if (MyAppDataManager.friendController)
            {
                MyAppDataManager.friendController.friendListArray = friendListArray;
                
                [MyAppDataManager.friendController transmitArrToDic:friendListArray];
                
                [MyAppDataManager.friendController.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
                [TKLoadingView dismissTkFromView:MyAppDataManager.friendController.navigationController.view animated:YES afterShow:0.0];
            }
        }
                else if([[resDic valueForKey:@"type"]isEqual:@"downLoadTheme"])
        {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"downLoadThemeComplete" object:self userInfo:resDic];
        }
        else if ([AppComManager respondsDic:resDic isFunctionData:BanBu_GetFaceStoreList])//表情商店
        {
            //刷新界面
            if (MyAppDataManager.emoStoreController)
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [MyAppDataManager.emoStoreController refreshView:resDic];
                    
                });
            }
        }
        else if ([AppComManager respondsDic:resDic isFunctionData:BanBu_AddCollectEmo_ByUser])//添加一个收藏的表情
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (MyAppDataManager.manuscriptController)
                {
                    [TKLoadingView showTkloadingAddedTo:MyAppDataManager.appChatController.navigationController.view title:NSLocalizedString(@"collectingSucceed", nil) activityAnimated:NO duration:1.2f];
                }
            });
            //下载收藏的表情信息
            NSMutableDictionary *loginDic = [NSMutableDictionary dictionaryWithCapacity:8];
            [loginDic setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
            [AppComManager getBanBuDataWIthCollectEmo:BanBu_GetCollectEmo_ByUser par:loginDic delegate:MyAppDataManager];
        }
        else if([AppComManager respondsDic:resDic isFunctionData:BanBu_GetCollectEmo_ByUser])//下载收藏的表情信息
        {
            NSMutableArray * collectedEmoArr = [NSMutableArray arrayWithArray:[resDic valueForKey:@"list"]];
            
            NSMutableDictionary * collectedEmoDic = [NSMutableDictionary dictionaryWithCapacity:8];
            
            for (int i = 0; i<collectedEmoArr.count;i++)
            {
                NSString * favid = [[collectedEmoArr objectAtIndex:i] valueForKey:KeyFavid];
                //2014年11月03日17:47:11 by yinlinlin 添加判断，从崩溃日志分析出的问题
                if ([[[collectedEmoArr objectAtIndex:i] valueForKey:KeyContent] isKindOfClass:[NSString class]])
                {
                    NSMutableDictionary * emoInfoDic = [NSMutableDictionary dictionaryWithDictionary:[AppComManager getAMsgFrom64String:[[collectedEmoArr objectAtIndex:i] valueForKey:KeyContent]]];
                    
                    [emoInfoDic setValue:favid forKey:KeyFavid];
                    
                    [collectedEmoDic setValue:emoInfoDic forKey:favid];
                }
                
            }
            
            [NSKeyedArchiver archiveRootObject:collectedEmoDic toFile:CollectEmoInfoPath];
            
            //刷新收藏的表情键盘
            [[NSNotificationCenter defaultCenter]postNotificationName:KRefreshCollectedEmo object:nil];
        }
        else if ([AppComManager respondsDic:resDic isFunctionData:BanBu_AddCollectAmsg_ByUser])//添加一个收藏的文本、图片、语音
        {
            //下载收藏的信息
            NSMutableDictionary *loginDic = [NSMutableDictionary dictionaryWithCapacity:8];
            [loginDic setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
            //重新请求第一页收藏的数据,2014/07/17
            [loginDic setValue:@"1" forKeyPath:@"pageno"];
            [AppComManager getBanBuDataWIthCollectEmo:BanBu_GetCollectAmsg_ByUser par:loginDic delegate:MyAppDataManager];
        }
        else if([AppComManager respondsDic:resDic isFunctionData:BanBu_GetCollectAmsg_ByUser])//下载收藏的文本、图片、语音信息
        {
            NSMutableArray * collectedAmsgArr = [NSMutableArray arrayWithArray:[resDic valueForKey:@"list"]];
            //没有新的数据2014/07/17
            if (!collectedAmsgArr.count)
            {
                //没有新的数据同样刷新一下
                [[NSNotificationCenter defaultCenter]postNotificationName:KNoRefreshCollectAmsg object:nil];
                return;
            }
            
            NSMutableDictionary * collectedAmsgDic = [[NSMutableDictionary alloc]init];
            
            //如果当前请求的数据不是第一页，将原来本地的数据取出来重新存储,2014/07/17
            if ([[resDic valueForKey:@"pageno"] intValue] > 1)
            {
                //原来存储的数据
                NSDictionary * collectedDic = [BanBu_CommUtils getLocalData:CollectDataKey];
                [collectedAmsgDic setValuesForKeysWithDictionary:collectedDic];
                
            }
            else
            {
                //设置第一页数据的缓存时间
                [BanBu_CommUtils setCacheTime:CollectTimeKey];//设置缓存时间
            }
            
            for (int i = 0; i<collectedAmsgArr.count;i++)
            {
                NSMutableDictionary * manuscriptDic =[NSMutableDictionary dictionaryWithDictionary:[collectedAmsgArr objectAtIndex:i]];
                NSString * content = [manuscriptDic valueForKey:KeyContent];
                
                NSData * data = [NSData dataFromBase64String:content];
                
//                content = [[CJSONDeserializer deserializer] deserialize:data error:nil];
                
                content = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
                
                [manuscriptDic setValue:content forKey:KeyContent];
                NSString * favid = [[collectedAmsgArr objectAtIndex:i] valueForKey:KeyFavid];
                
                [collectedAmsgDic setValue:manuscriptDic forKey:favid];
                NSLog(@"%d",[collectedAmsgDic allKeys].count);
            }
            
            //修改存储方法修改
//            [NSKeyedArchiver archiveRootObject:collectedAmsgDic toFile:CollectedAmsgInfoPath];
            [BanBu_CommUtils setCacheTime:CollectTimeKey];//设置缓存时间
            [BanBu_CommUtils setLocalData:collectedAmsgDic key:CollectDataKey];//保存数据至本地
            //保存请求收藏数据的页码,2014/07/17
            [BanBu_CommUtils setLocalData:[NSNumber numberWithInt:[[resDic valueForKey:@"pageno"] intValue]] key:CollectPageKey];

            //刷新收藏的信息
            [[NSNotificationCenter defaultCenter]postNotificationName:KFinishDownloadingAmsg object:nil];
            [[NSNotificationCenter defaultCenter]postNotificationName:KFinishCollecttingAmsg object:nil];
        }
        else if ([AppComManager respondsDic:resDic isFunctionData:BanBu_Get_MagicChatSystemList])//获取魔法文字的所有素材
        {
            NSLog(@"resDic:%@",resDic);
            NSDictionary * magicWordsDic = resDic;
            //zyfzyfzyf⬇️
            NSUserDefaults * defau=[NSUserDefaults standardUserDefaults];
            [defau setObject:magicWordsDic forKey:@"magicWords"];
            [defau synchronize];
            //zyfzyfzyf⬆️
            [NSKeyedArchiver archiveRootObject:magicWordsDic toFile:MagicWordsInfoPath];
        }
    }
    else
    {//ok 为no
        if([AppComManager respondsDic:resDic isFunctionData:BanBu_SendMessage_To_Server_V2])//发消息后处理返回
        {
            NSString * errorInfo = [MyAppDataManager IsInternationalLanguage:[resDic objectForKey:@"error"]];

            if (errorInfo == nil)
            {
//                [TKLoadingView showTkloadingAddedTo:MyAppDataManager.appChatController.navigationController.view title:NSLocalizedString(@"network_unavailabel", nil) activityAnimated:NO duration:1.0];
            }
            else
            {
                [TKLoadingView showTkloadingAddedTo:MyAppDataManager.appChatController.navigationController.view title:errorInfo activityAnimated:NO duration:3.0];
            }
            
            NSDictionary *statuDic =  [NSDictionary dictionaryWithObjectsAndKeys:@"fail",@"status",[resDic valueForKey:@"touid"],@"touid",[resDic valueForKey:KeyChatid],KeyChatid,[NSNumber numberWithInteger:MediaStatusNormal],KeyMediaStatus, nil];
            //转发消息，touid是多个id
            [self setStatusOfAllBySend:statuDic];
            
            //判断这条消息，还是这个人的嘛（self.dialogs可能已改变）
            if(MyAppDataManager.appChatController && [[NSString stringWithFormat:@",%@,",[resDic valueForKey:KeyUid]] rangeOfString:[NSString stringWithFormat:@",%@,",MyAppDataManager.chatuid]].location != NSNotFound)
            {
                NSString * chatid = @"";
                
                if ([[resDic valueForKey:KeyChatid]isKindOfClass:[NSDictionary class]])
                {
                    chatid = [[resDic valueForKey:KeyChatid] valueForKey:MyAppDataManager.chatuid];
                }
                else if ([[resDic valueForKey:KeyChatid]isKindOfClass:[NSString class]])
                {
                    chatid = [resDic valueForKey:KeyChatid];
                }
                
                NSInteger row = [[MyAppDataManager.cellRowMapDic valueForKey:chatid] integerValue];
                NSMutableDictionary *amsg = [NSMutableDictionary dictionaryWithDictionary:[self.dialogs objectAtIndex:row]];
                [amsg setValue:[NSNumber numberWithInteger:ChatStatusSendFail] forKey:KeyStatus];
                [amsg setValue:[NSNumber numberWithInteger:MediaStatusNormal] forKey:KeyMediaStatus];
                [self.dialogs replaceObjectAtIndex:row withObject:amsg];

                [MyAppDataManager.appChatController.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
            }
            else
            {
                [MyAppDataManager readTalkList:nil WithNumber:0];
            }
        }
    }
}

- (void)banbuRequestNamed:(NSString *)requestname uploadDataProgress:(float)progress
{
    //    if(self.appChatController)
    //    {
    //        NSInteger row = [[[requestname componentsSeparatedByString:@"-"] objectAtIndex:0] integerValue];
    //
    //
    //        int rowt=MyAppDataManager.talkArr.count-row;
    //
    //        int dilogsRow=MyAppDataManager.dialogs.count-rowt;
    //
    //        NSLog(@"- =- =- =- =- = -= -= -= - %d",dilogsRow);
    //
    //        BanBu_ChatCell *cell = (BanBu_ChatCell *)[MyAppDataManager.appChatController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:dilogsRow inSection:0]];
    //        if(cell)
    //        {
    //            // 判断是不是照片或者录音
    //            if(![[requestname pathExtension] isEqual:@"amr"]){
    //
    //                [cell.mediaView setMedia:requestname];
    //
    //
    //
    //            }else
    //            {
    //
    //                NSLog(@"ha ha ha  this is ))))((())_(_()_)_)");
    //
    //            }
    //
    //        }
    //    }
}
#pragma mark - 封装规范的消息发送
- (void)banbuUploadRequest:(NSDictionary *)resDic didFinishedWithError:(NSError *)error
{
    if(error)
    {
        NSDictionary *statuDic =  [NSDictionary dictionaryWithObjectsAndKeys:@"fail",@"status",[resDic valueForKey:@"touid"],@"touid",[resDic valueForKey:KeyChatid],KeyChatid,[NSNumber numberWithInteger:MediaStatusUploadFaild],KeyMediaStatus, nil];
        [self setStatusOfOne:statuDic];
        
        if(MyAppDataManager.appChatController &&[self.chatuid isEqualToString:[resDic valueForKey:KeyUid]])
        {
            NSInteger row = [[MyAppDataManager.cellRowMapDic valueForKey:[resDic valueForKey:KeyChatid]] integerValue];
            NSMutableDictionary *amsg = [NSMutableDictionary dictionaryWithDictionary:[self.dialogs objectAtIndex:row]];
            [amsg setValue:[NSNumber numberWithInteger:ChatStatusSendFail] forKey:KeyStatus];
            [amsg setValue:[NSNumber numberWithInteger:MediaStatusUploadFaild] forKey:KeyMediaStatus];
            [self.dialogs replaceObjectAtIndex:row withObject:amsg];
            [MyAppDataManager.appChatController.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
        }
        return;
    }
    
    if([[resDic valueForKey:@"ok"] boolValue])
    {
        //上传成功后，更改自定义的文件名（chatid.jpg）为服务器返回的内容
        NSInteger row = [[MyAppDataManager.cellRowMapDic valueForKey:[resDic valueForKey:KeyChatid]] integerValue];
        NSMutableDictionary *amsg;
        
        if(MyAppDataManager.appChatController &&[self.chatuid isEqualToString:[resDic valueForKey:KeyUid]])
        {//点对点
            amsg = [NSMutableDictionary dictionaryWithDictionary:[self.dialogs objectAtIndex:row]];
            [amsg setValue:[NSNumber numberWithInteger:MediaStatusNormal] forKey:KeyMediaStatus];
            [amsg setValue:[resDic valueForKey:KeyChatid] forKey:KeyChatid];
            
            NSMutableDictionary *peoDic = [NSMutableDictionary dictionaryWithDictionary:amsg];
            [peoDic setValue:[resDic valueForKey:KeyUid] forKey:KeyFromUid];
            
            if (!(row < MyAppDataManager.cellRowMapDic.count - 1))
            {
                [self setTalkPeopleOne:peoDic];
            }
            
            if ([[resDic valueForKey:@"mediatype"] isEqualToString:@"image"] && [[resDic valueForKey:@"thumbnail"] isEqualToString:@"thumbnail"])
            {
                [amsg setValue:[resDic valueForKey:@"fileurl"] forKey:KeyThumbnail];
                [self setThumbnailOne:amsg andToUid:[resDic valueForKey:KeyUid]];
                
                if ([VALUE(KeyContent, amsg) hasSuffix:@"mp4"])
                {
                    NSMutableDictionary *saysDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:VALUE(KeyContent, amsg),KeyContent,[resDic valueForKey:@"mediatype"],KeyType,[amsg valueForKey:KeyShowFrom],KeyShowFrom,[NSNumber numberWithInteger:MyAppDataManager.selectedBubbleIndex],KeyBubbleID,VALUE(KeyThumbnail, amsg),KeyThumbnail,nil];
                    [saysDic setValue:[NSNumber numberWithInt:sendMsgManager.effectiveTime] forKey:KeyEffectiveTime];
                    
                    [self sendMsg:[NSDictionary dictionaryWithObjectsAndKeys:saysDic,KeySays,VALUE(KeyChatid, amsg),KeyChatid, nil] toUid:[resDic valueForKey:KeyUid]];
                }
            }
            else
            {
                [amsg setValue:[resDic valueForKey:@"fileurl"] forKey:KeyContent];
                [self setDialogOne:amsg andToUid:[resDic valueForKey:KeyUid]];
                if ([VALUE(KeyThumbnail, amsg) hasSuffix:@"jpg"] || [VALUE(KeyType, resDic) integerValue] != ChatCellTypeVideo)
                {
                    NSMutableDictionary *saysDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:VALUE(KeyContent, amsg),KeyContent,[resDic valueForKey:@"mediatype"],KeyType,[amsg valueForKey:KeyShowFrom],KeyShowFrom,[NSNumber numberWithInteger:MyAppDataManager.selectedBubbleIndex],KeyBubbleID,VALUE(KeyThumbnail, amsg),KeyThumbnail,nil];
                    [saysDic setValue:[NSNumber numberWithInt:sendMsgManager.effectiveTime] forKey:KeyEffectiveTime];
                    
                    [self sendMsg:[NSDictionary dictionaryWithObjectsAndKeys:saysDic,KeySays,VALUE(KeyChatid, amsg),KeyChatid, nil] toUid:[resDic valueForKey:KeyUid]];
                }
            }
            if(self.dialogs.count>row)
            {
                [self.dialogs replaceObjectAtIndex:row withObject:amsg];
                [MyAppDataManager.appChatController.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
            }
        }
        else
        {
            NSMutableArray * dialogsArray = [self readTalkListAfterSendImage:[resDic valueForKey:KeyUid] WithNumber:row + 1];
            amsg = [NSMutableDictionary dictionaryWithDictionary:[dialogsArray objectAtIndex:row]];
            
            [amsg setValue:[resDic valueForKey:@"fileurl"] forKey:KeyContent];
            [amsg setValue:[NSNumber numberWithInteger:MediaStatusNormal] forKey:KeyMediaStatus];
            [amsg setValue:[resDic valueForKey:KeyChatid] forKey:KeyChatid];
            
            NSMutableDictionary *peoDic = [NSMutableDictionary dictionaryWithDictionary:amsg];
            [peoDic setValue:[resDic valueForKey:KeyUid] forKey:KeyFromUid];
            if (!(row<MyAppDataManager.cellRowMapDic.count))
            {
                [self setTalkPeopleOne:peoDic];
            }
            
            if ([[resDic valueForKey:@"mediatype"] isEqualToString:@"image"] && [[resDic valueForKey:@"thumbnail"] isEqualToString:@"thumbnail"])
            {
                [amsg setValue:[resDic valueForKey:@"fileurl"] forKey:KeyContent];
                [self setThumbnailOne:amsg andToUid:[resDic valueForKey:KeyUid]];
            }
            else
            {
                [self setDialogOne:amsg andToUid:[resDic valueForKey:KeyUid]];
                NSMutableDictionary *saysDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:VALUE(KeyContent, amsg),KeyContent,[resDic valueForKey:@"mediatype"],KeyType,[amsg valueForKey:KeyShowFrom],KeyShowFrom,[NSNumber numberWithInteger:MyAppDataManager.selectedBubbleIndex],KeyBubbleID,VALUE(KeyThumbnail, amsg),KeyThumbnail,nil];
                [saysDic setValue:[NSNumber numberWithInt:sendMsgManager.effectiveTime] forKey:KeyEffectiveTime];
                
                [self sendMsg:[NSDictionary dictionaryWithObjectsAndKeys:saysDic,KeySays,VALUE(KeyChatid, amsg),KeyChatid, nil] toUid:[resDic valueForKey:KeyUid]];
            }
        }
    }
}

- (void)banbuDownloadRequest:(NSDictionary *)resDic didFinishedWithError:(NSError *)error
{
    if(error)
    {
        NSDictionary *statuDic =  [NSDictionary dictionaryWithObjectsAndKeys:@"fail",@"status",[resDic valueForKey:@"touid"],@"touid",[resDic valueForKey:KeyChatid],KeyChatid,[NSNumber numberWithInteger:MediaStatusDownloadFaild],KeyMediaStatus, nil];
        [self setStatusOfOne:statuDic];
        
        if(MyAppDataManager.appChatController &&[self.chatuid isEqualToString:[resDic valueForKey:KeyUid]])
        {
            NSInteger row = [[MyAppDataManager.cellRowMapDic valueForKey:[resDic valueForKey:KeyChatid]] integerValue];
            NSMutableDictionary *amsg = [NSMutableDictionary dictionaryWithDictionary:[self.dialogs objectAtIndex:row]];
            [amsg setValue:[NSNumber numberWithInteger:ChatStatusNone] forKey:KeyStatus];
            [amsg setValue:[NSNumber numberWithInteger:MediaStatusDownloadFaild] forKey:KeyMediaStatus];
            [self.dialogs replaceObjectAtIndex:row withObject:amsg];
            [MyAppDataManager.appChatController.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
        }
        return;
    }
    
    if([[resDic valueForKey:@"ok"] boolValue])
    {
        if ([[resDic valueForKey:@"thumbnail"] isEqual:@"thumbnail"])
        {
            return;
        }
        
        NSDictionary *statuDic =  [NSDictionary dictionaryWithObjectsAndKeys:@"none",@"status",[resDic valueForKey:@"touid"],@"touid",[resDic valueForKey:KeyChatid],KeyChatid,[NSNumber numberWithInteger:MediaStatusNormal],KeyMediaStatus, nil];
        [self setStatusOfOne:statuDic];
        
        double height = 0;
        
        NSString * path = [[resDic valueForKey:@"mediaUrlStr"] pathExtension];
        if([path isEqualToString:@"jpg"] ||[path isEqualToString:@"png"] || [path isEqualToString:@"gif"])
        {
            if (![[resDic valueForKey:@"thumbnail"] isEqual:@"thumbnail"])
            {
                if (![[resDic valueForKey:@"type"]isEqualToString:@"magicFace"])
                {//当没有type时说明下载的不是魔法表情，需要重设高度
                    height = [MyAppDataManager setReceiveImageHeight:resDic];
                }
            }
        }
        
        if(MyAppDataManager.appChatController &&[self.chatuid isEqualToString:[resDic valueForKey:KeyUid]])
        {
            NSInteger row = [[MyAppDataManager.cellRowMapDic valueForKey:[resDic valueForKey:KeyChatid]] integerValue];
            NSMutableDictionary *amsg = [NSMutableDictionary dictionaryWithDictionary:[self.dialogs objectAtIndex:row]];
            
            [amsg setValue:[NSNumber numberWithInteger:MediaStatusNormal] forKey:KeyMediaStatus];
            
            if([[[resDic valueForKey:@"mediaUrlStr"] pathExtension]isEqualToString:@"jpg"] ||[[[resDic valueForKey:@"mediaUrlStr"] pathExtension]isEqualToString:@"png"] ||[[[resDic valueForKey:@"mediaUrlStr"] pathExtension]isEqualToString:@"gif"])
            {
                if (![[resDic valueForKey:@"thumbnail"] isEqual:@"thumbnail"])
                {
                    if (![[resDic valueForKey:@"type"]isEqualToString:@"magicFace"])
                    {
                        [amsg setValue:[NSNumber numberWithDouble:height] forKey:KeyHeight];
                    }
                }
            }
            
            [self.dialogs replaceObjectAtIndex:row withObject:amsg];
            [MyAppDataManager.appChatController.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
        }
    }
}

- (void)banbuRequestNamed:(NSDictionary *)resDic downloadDataProgress:(float)progress
{
    NSString * requestname = [resDic valueForKey:@"requestname"];
    if(MyAppDataManager.appChatController && [self.chatuid isEqualToString:[resDic valueForKey:KeyUid]])
    {
        NSInteger row = [[[requestname componentsSeparatedByString:@"-"] objectAtIndex:0] integerValue];
        int rowt=MyAppDataManager.talkArr.count-row;
        
        int dilogsRow=MyAppDataManager.dialogs.count-rowt;
        
        BanBu_ChatSmileCell *cell = (BanBu_ChatSmileCell *)[MyAppDataManager.appChatController.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:dilogsRow inSection:0]];
        
        if(cell)
        {
            if(![[requestname pathExtension] isEqual:@"amr"])
            {
            }
            else
            {
                // 这里是下载过程中的进度条
                NSLog(@"ha ha ha  this is ))))((())_(_()_)_)");
            }
        }
    }
}

#pragma mark -
+(id)allocWithZone:(NSZone *)zone{
    @synchronized(self){
        if (sharedAppDataManager == nil) {
            sharedAppDataManager = [super allocWithZone:zone];
            return  sharedAppDataManager;
        }
    }
    return nil;
}


- (BOOL)fiveMinuteLater:(NSString *)stime beforeTime:(NSString *)ltime
{
    if(!ltime || !stime)
        return NO;
    
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *currentDate = [formatter dateFromString:stime];
    if(!currentDate)
        return NO;
    NSDate *lastDate = [formatter dateFromString:ltime];
    if(!lastDate)
        return NO;
    
    return [currentDate timeIntervalSince1970]>[lastDate timeIntervalSince1970]+180;
}

-(NSString *)currentTime:(NSString *)receiveTime
{
    
    int hostTime=[[UserDefaults valueForKey:@"hostTime"] intValue];
    
    NSTimeInterval secondsPerDay = hostTime* 60;
    
    // 获取一个时间
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *currentDate = [formatter dateFromString:receiveTime];
    // 加上我们的当前时间
    NSString *stime = [formatter stringFromDate:[NSDate dateWithTimeInterval:secondsPerDay sinceDate:currentDate]];
    return stime;
}
-(NSString*)currentTimeBeforeAweek
{
    NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init]autorelease];
    NSDate *nowDate = [NSDate date];
    NSTimeInterval  interval = 24*60*60*7; //1:天数
    NSDate *date1 = [nowDate dateByAddingTimeInterval:-interval];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    return  ([NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:date1]]);
}

- (UIImage *)scaleImage:(UIImage *)image proportion:(float)scale {
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width/scale, image.size.height/scale));
    CGRect imageRect = CGRectMake(0.0, 0.0, image.size.width/scale, image.size.height/scale);
    [image drawInRect:imageRect];
    image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

-(NSString *)UserDefautsKey:(int )from
{
    NSString *fr=[NSString stringWithFormat:@"%d",from*100+from*10+123];
    
    return [@"amsg" stringByAppendingString:fr];
}


- (id)copyWithZone:(NSZone *)zone
{
    return self;
}
- (id)retain
{
    return self;
}
- (NSUInteger)retainCount
{
    return NSUIntegerMax;  //denotes an object that cannot be released
}
- (oneway void)release
{
    //do nothing
}
- (id)autorelease
{
    return self;
}

#pragma mark - 个人资料表的操作
-(void)initPersonalDataDB
{
    if(![_dataBase goodConnection])
        [_dataBase open];
    
    if(![_dataBase tableExists:PersonalDataList])
    {
        NSDictionary *queryDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                  DBFieldType_TEXT,         KeyFromUid,
                                  DBFieldType_TEXT,         keyPersonalInfo,
                                  DBFieldType_INTEGER,      keyUpdateTime,
                                  nil];
        NSString *query = [NSString stringWithFormat:@"CREATE TABLE %@ (%@ , PRIMARY KEY(userid ASC))",PersonalDataList,[self getPar1StrFromDic:queryDic]];
        
        BOOL ff = [_dataBase executeUpdate:query];
        if(!ff)
        {
            NSLog(@"初始化个人资料表失败%@",[[_dataBase lastError] description]);
        }
    }
}

-(void)deletePersonalDataWithUsers:(NSArray *)_users
{
    NSString *allUserid = [_users componentsJoinedByString:@","];
    NSString *query = [NSString stringWithFormat:@"DELETE FROM %@ WHERE userid in(%@)",PersonalDataList,allUserid];
    BOOL s = [_dataBase executeUpdate:query];
    if(!s)
    {
        NSLog(@"deletePersonalDataWithUsers 删除个人资料database action error:%@",[[_dataBase lastError] description]);
    }
}

//往个人资料表添加数据
-(void)writePersonalDataToDB:(NSArray *)personalDataList
{
    [self initPersonalDataDB];
    NSMutableArray *deleteArray = [NSMutableArray array];
    for(NSDictionary *parDic in personalDataList)
    {
        if ([parDic valueForKey:keyPersonalInfo])
        {
            [deleteArray addObject:[parDic objectForKey:@"userid"]];
        }
    }
    [self deletePersonalDataWithUsers:deleteArray];
    
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setLocale:[NSLocale currentLocale]];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString *stime1 = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSinceDate:[formatter dateFromString:@"2013-01-01 12:00:00"]]];
    NSNumber *stime = [NSNumber numberWithInteger:[stime1 integerValue]];
    NSMutableString *query = [NSMutableString stringWithFormat:@"INSERT INTO %@ (userid,userinfor,updatetime) ",PersonalDataList];
    for(NSDictionary *personalData in personalDataList)
    {
        if (VALUE(keyPersonalInfo, personalData))
        {
            NSString *personalInfo = [[CJSONSerializer serializer] serializeDictionary: VALUE(keyPersonalInfo, personalData)];
            personalInfo = [[personalInfo dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
            [query appendFormat:@"SELECT '%@','%@',%@      UNION ",VALUE(KeyFromUid, personalData),personalInfo,stime];
        }
    }
    [query deleteCharactersInRange:NSMakeRange(query.length-8, 8)];
    
    if (query.length<100)
    {
        return;
    }
    BOOL s1 = [_dataBase executeUpdate:query];
    if(!s1)
    {
        NSLog(@"writePersonalDataToDB database action error:%@",[[_dataBase lastError] description]);
    }
}

-(NSMutableArray *)getPersonalDataIn:(NSString *)_minute
{
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setLocale:[NSLocale currentLocale]];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *stime1 = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSinceDate:[formatter dateFromString:@"2013-01-01 12:00:00"]]-([_minute integerValue]*60)];
    NSNumber *stime = [NSNumber numberWithInteger:[stime1 integerValue]];
    NSMutableArray *dataList = [[[NSMutableArray alloc] initWithCapacity:10] autorelease];
    
    NSString *query = [NSString stringWithFormat:@"SELECT userid FROM %@ WHERE (updatetime >= %@) order by updatetime desc",PersonalDataList,stime];
    FMResultSet *rs = [_dataBase executeQuery:query];
    while ([rs next])
    {
        [dataList addObject:[rs stringForColumn:KeyFromUid]];
    }
    
    return dataList;
}

-(NSArray *)getPersonInfo:(NSArray *)useridList
{
    NSMutableArray * userInfoList = [NSMutableArray arrayWithCapacity:10];
    
    NSString * useridListStr= [useridList componentsJoinedByString:@","];
    NSString *query = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE userid in(%@)",PersonalDataList,useridListStr];
    FMResultSet *rs = [_dataBase executeQuery:query];
    
    while ([rs next])
    {
        NSMutableDictionary * userInfoDic = nil;
        
        NSString * userInfo = [rs stringForColumn:keyPersonalInfo];
        
        NSData *temp = [NSData dataFromBase64String:userInfo];
        
        userInfoDic=[[CJSONDeserializer deserializer] deserializeAsDictionary:temp error:nil];
        
        [userInfoList addObject:userInfoDic];
    }
    return userInfoList;
}

-(NSArray *)getPersonalDataOfUserid:(NSArray *)_users
{
    NSMutableArray *dataList = [[[NSMutableArray alloc] initWithCapacity:10] autorelease];
    
    if(_users.count)
    {
        NSString *allUserid = [_users componentsJoinedByString:@","];
        NSString *query = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE userid in(%@)",PersonalDataList,allUserid];
        FMResultSet *rs = [_dataBase executeQuery:query];
        while ([rs next])
        {
            NSDictionary *amsg = [NSDictionary dictionaryWithObjectsAndKeys:
                                  [rs stringForColumn:KeyFromUid],                         KeyFromUid,
                                  [rs stringForColumn:keyPersonalInfo],                    keyPersonalInfo,
                                  [rs stringForColumn:keyUpdateTime],                      keyUpdateTime,nil];
            
            NSData *temp = [NSData dataFromBase64String:[amsg valueForKey:keyPersonalInfo]];
            NSDictionary *arr=[[NSDictionary alloc]initWithDictionary:[[CJSONDeserializer deserializer] deserializeAsDictionary:temp error:nil]];
            
            NSMutableDictionary *dic=[NSMutableDictionary dictionaryWithDictionary:amsg];
            [dic setValue:arr forKey:keyPersonalInfo];
            [arr release];
            
            [dataList addObject:dic];
        }
    }
    else
    {
        NSString *query = [NSString stringWithFormat:@"SELECT * FROM %@",PersonalDataList];
        FMResultSet *rs = [_dataBase executeQuery:query];
        while ([rs next])
        {
            NSDictionary *amsg = [NSDictionary dictionaryWithObjectsAndKeys:
                                  [rs stringForColumn:KeyFromUid],                                KeyFromUid,
                                  [rs stringForColumn:keyPersonalInfo],                           keyPersonalInfo,
                                  [rs stringForColumn:keyUpdateTime],                             keyUpdateTime,nil];
            
            NSData *temp = [NSData dataFromBase64String:[amsg valueForKey:keyPersonalInfo]];
            NSDictionary *arr=[[NSDictionary alloc]initWithDictionary:[[CJSONDeserializer deserializer] deserializeAsDictionary:temp error:nil]];
            NSMutableDictionary *dic=[NSMutableDictionary dictionaryWithDictionary:amsg];
            [dic setValue:arr forKey:keyPersonalInfo];
            [arr release];
            [dataList addObject:dic];
        }
    }
    
    return dataList;
}


//更新个人资料表在线时间
-(void)updateLastOnlineTimeAndDistanceOfPersonalDB:(NSArray *)_updateInfo
{
    dispatch_queue_t queue;
    queue = dispatch_queue_create("com.update.MyQueue", nil);
    
    NSMutableArray *useridList = [[NSMutableArray alloc] init];
    for(int i = 0;i<_updateInfo.count;i++)
    {
        [useridList addObject:[[_updateInfo objectAtIndex:i] valueForKey:@"userid"]];
    }
    
    NSArray *personalDataList = [self getPersonalDataOfUserid:useridList];
    [useridList release];
    
    NSMutableArray *updatePersonList = [NSMutableArray arrayWithCapacity:100];
    NSMutableArray *updatePersonList1 = [NSMutableArray arrayWithCapacity:100];
    
    _updateInfo = [_updateInfo sortedArrayUsingComparator: ^(id obj1, id obj2) {
        return [[obj2 objectForKey:@"userid"] compare:[obj1 objectForKey:@"userid"] options:NSCaseInsensitiveSearch];
        
    }];
    personalDataList = [personalDataList sortedArrayUsingComparator: ^(id obj1, id obj2) {
        return [[obj2 objectForKey:@"userid"] compare:[obj1 objectForKey:@"userid"] options:NSCaseInsensitiveSearch];
        
    }];
    
    for(int i=0;i<personalDataList.count;i++)
    {
        NSMutableDictionary *personalData = [NSMutableDictionary dictionaryWithDictionary:[[personalDataList objectAtIndex:i] valueForKey:keyPersonalInfo]];
        
        if(personalData.count<4)
        {
            continue;
        }

        NSString * ltime =[[_updateInfo objectAtIndex:i] valueForKey:@"ltime"];
        NSString * dmeter = [[_updateInfo objectAtIndex:i] valueForKey:@"dmeter"];
        NSString * dtime = [[_updateInfo objectAtIndex:i] valueForKey:@"dtime"];
        
        [personalData setValue:ltime forKey:@"ltime"];
        [personalData setValue:dmeter forKey:@"dmeter"];
        [personalData setValue:dtime forKey:@"dtime"];

        [updatePersonList addObject:personalData];
        [updatePersonList1 addObject:personalData];
        
        if((i+1)%10==0 || i+1==_updateInfo.count)
        {
            __block NSArray *list = [[NSArray alloc] initWithArray:updatePersonList];
            dispatch_async(queue, ^{
                for(NSDictionary *person in list)
                {
                    [self updateDataOfTimeAndDistance:person];
                }
            });
            [updatePersonList removeAllObjects];
        }
    }
}

-(void)updateDataOfTimeAndDistance:(NSDictionary *)_personalData
{
    if (![_dataBase goodConnection])
    {
        [_dataBase open];
    }
    NSString *query = [NSString stringWithFormat:@"UPDATE %@ set userinfor = ? WHERE userid = %@",PersonalDataList,[_personalData valueForKey:@"userid"]];
    NSString *personalInfo = [[CJSONSerializer serializer] serializeDictionary:_personalData];
    personalInfo = [[personalInfo dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    BOOL s1 = [_dataBase executeUpdate:query,personalInfo];
    if(!s1)
    {
        NSLog(@"updateDataOfTimeAndDistance 更新失败");
    }
}

-(NSTimeInterval )getTheSecondLastOnlineTime:(NSString *)_lastOnlineTime
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *lOnlineTime = [formatter dateFromString:_lastOnlineTime];
    //    NSDate *timeDif     = [formatter dateFromString:_timeDifference];
    //    if(_timeDifference)
    NSDate *serverTime  = [NSDate dateWithTimeIntervalSinceNow:_timeDifference];
    NSTimeInterval timeInterval = [serverTime timeIntervalSinceDate:lOnlineTime];
    [formatter release];
    return timeInterval;
}

-(NSString *)getServerTime
{
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *serverTime  = [NSDate dateWithTimeIntervalSinceNow:_timeDifference];
    NSString *serverTimeString = [formatter stringFromDate:serverTime];
    return serverTimeString;
}

-(NSString *)getTheLastOnlineTime :(NSString *)_lastOnlineTime;
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *lOnlineTime = [formatter dateFromString:_lastOnlineTime];
    [formatter release];
    NSDate *serverTime  = [NSDate dateWithTimeIntervalSinceNow:_timeDifference];
    NSTimeInterval timeInterval = [serverTime timeIntervalSinceDate:lOnlineTime];
    if([_lastOnlineTime isEqual:@"__hide__"])
    {
        return [MyAppDataManager IsInternationalLanguage:@"__hide__"];
    }
    if(timeInterval <60)
    {
        return [NSString stringWithFormat:@"1%@",NSLocalizedString(@"minuteAgo", nil)];
    }
    else
        if(timeInterval <=3600)
        {
            return [NSString stringWithFormat:@"%d%@",(int)timeInterval/60,NSLocalizedString(@"minuteAgo", nil)];
        }
        else
            if(timeInterval <3600*24)
            {
                return [NSString stringWithFormat:@"%d%@",(int)timeInterval/3600,NSLocalizedString(@"hourAgo", nil)];
            }
            else
                if(timeInterval <3600*24*3)
                {
                    return [NSString stringWithFormat:@"%d%@",(int)timeInterval/3600/24,NSLocalizedString(@"dayAgo", nil)];
                }
                else
                {
                    return [NSString stringWithFormat:@"3%@",NSLocalizedString(@"dayAgo", nil) ];
                }
}

-(BOOL)initSystemPerson:(NSDictionary *)personalData
{
    if (![_dataBase goodConnection])
    {
        [_dataBase open];
    }
    
    NSString * selectQuery = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE userid = 600",PersonalDataList];
    
    FMResultSet * rs = [_dataBase executeQuery:selectQuery];
    BOOL bl = YES;
    while([rs next])
    {
        bl = NO;
    }
    
    if (!bl)//数据库中有600号的个人资料
    {
        return YES;
    }
    //没找到时插入数据库
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setLocale:[NSLocale currentLocale]];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString *stime1 = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSinceDate:[formatter dateFromString:@"2013-01-01 12:00:00"]]];
    NSNumber *stime = [NSNumber numberWithInteger:[stime1 integerValue]];
    
    NSMutableDictionary * userInfo = [NSMutableDictionary dictionaryWithCapacity:20];
    [userInfo setValue:@"165-170" forKey:KeyHbody];
    [userInfo setValue:@"" forKey:KeyLovego];
    [userInfo setValue:@"600" forKey:KeyFromUid];
    [userInfo setValue:@"http://file.koochat.com/photo-user-face/sysface_sayhi.jpg" forKey:KeyUface];
    [userInfo setValue:@"射手座" forKey:KeySstar];
    [userInfo setValue:@"50-60" forKey:KeyWbody];
    [userInfo setValue:@"" forKey:KeyFacelist];
    [userInfo setValue:@"x" forKey:KeyXblood];
    [userInfo setValue:@"12794公里" forKey:KeyDmeter];
    [userInfo setValue:@"" forKey:KeyLiked];
    [userInfo setValue:@"失去的东西总会以另外一种形式再回来" forKey:KeySayme];
    [userInfo setValue:@"" forKey:KeyCompany];
    [userInfo setValue:@"m" forKey:KeyGender];
    [userInfo setValue:@"" forKey:KeySchool];
    [userInfo setValue:@"2013-09-06 17:09:52" forKey:KeyOnLinetime];
    [userInfo setValue:@"陌生人打招呼" forKey:KeyUname];
    [userInfo setValue:@"" forKey:KeyJobtitle];
    [userInfo setValue:@"飞机 16小时" forKey:@"dtime"];
    [userInfo setValue:@"12" forKey:KeyOldyears];
    
    NSString *personalInfo = [[CJSONSerializer serializer] serializeDictionary: userInfo];
    personalInfo = [[personalInfo dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    NSMutableString *query = [NSMutableString stringWithFormat:@"INSERT INTO %@ (userid,userinfor,updatetime) ",PersonalDataList];
    
    [query appendFormat:@"VALUES('%@','%@',%@)",@"600",personalInfo,stime];
    
    bl = [_dataBase executeUpdate:query];
    if (!bl)
    {
        NSLog(@"writePersonalDataToDB database action error:%@",[[_dataBase lastError] description]);
    }
    return bl;
}

//获取用户资料
-(NSDictionary *)getUserinfo:(NSString *)userid
{
    NSMutableDictionary * userInfoDic2 = [NSMutableDictionary dictionaryWithCapacity:4];
    NSString *query = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE userid in(%@)",PersonalDataList,userid];
    FMResultSet *rs = [_dataBase executeQuery:query];
    
    while ([rs next])
    {
        NSString * userinfo = [rs stringForColumn:keyPersonalInfo];
        NSData *temp = [NSData dataFromBase64String:userinfo];
        
        NSDictionary * userInfoDic1 = [[CJSONDeserializer deserializer] deserializeAsDictionary:temp error:nil];
        
        [userInfoDic2 setValue:[userInfoDic1 valueForKey:KeyUface] forKey:KeyUface];
        [userInfoDic2 setValue:[MyAppDataManager IsInternationalLanguage:[MyAppDataManager theRevisedName:[userInfoDic1 valueForKey:KeyPname] andUID:userid]] forKey:KeyPname];
        ;
        
        //2014年11月13日11:54:40 by yinlinlin 添加地理位置
        [userInfoDic2 setValue:[userInfoDic1 valueForKey:@"incityofname"] forKey:@"incityofname"];
        [userInfoDic2 setValue:[userInfoDic1 valueForKey:KeyGender] forKey:KeyGender];
        [userInfoDic2 setValue:[userInfoDic1 valueForKey:KeyAge] forKey:KeyAge];
        [userInfoDic2 setValue:[userInfoDic1 valueForKey:KeyDmeter] forKey:KeyDmeter];
        [userInfoDic2 setValue:[userInfoDic1 valueForKey:@"userlevel"] forKey:@"userlevel"];
        [userInfoDic2 setValue:[userInfoDic1 valueForKey:KeySstar] forKey:KeySstar];
        [userInfoDic2 setValue:[userInfoDic1 valueForKey:@"verify"] forKey:@"verify"];
    }
    
    return userInfoDic2;
}

//从对话表获取个人资料，获取不到时从个人资料表中获取
-(NSDictionary *)getUserinfoFromTalk:(NSString *)userid
{
    NSMutableDictionary * userInfoDic2 = [NSMutableDictionary dictionaryWithDictionary:[self getUserinfoDic:userid]];
    
    if ([[userInfoDic2 valueForKey:keyPersonalInfo] length] <10)
    {
        //从数据库对话表表获取个人资料
        NSString *query = [NSString stringWithFormat:@"SELECT userinfor,dmeter FROM %@ WHERE userid in(%@)",PersonalDataList,userid];
        FMResultSet *rs = [_dataBase executeQuery:query];
        
        while ([rs next])
        {
            NSString * userinfo = [rs stringForColumn:keyPersonalInfo];
            NSString * dmeter = [rs stringForColumn:KeyDmeter];
            
            [userInfoDic2 setValue:userinfo forKey:keyPersonalInfo];
            [userInfoDic2 setValue:dmeter forKey:KeyDmeter];
        }
    }
    
    return userInfoDic2;
}

//转发多人时提取用户资料和距离
-(NSDictionary *)getUserinfoDic:(NSString *)userid
{
    NSMutableDictionary * userInfoDic = [NSMutableDictionary dictionaryWithCapacity:7];
    NSString *query = [NSString stringWithFormat:@"SELECT userid,userinfor,dmeter FROM %@ WHERE userid in(%@)",TALKPEOPLES,userid];
    FMResultSet *rs = [_dataBase executeQuery:query];
    
    while ([rs next])
    {
        NSString * userinfo = [rs stringForColumn:keyPersonalInfo];
        NSString * userid = [rs stringForColumn:KeyFromUid];
        NSString * dmeter = [rs stringForColumn:KeyDmeter];
        
        NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:userinfo,keyPersonalInfo,dmeter,KeyDmeter, nil];
        [userInfoDic setValue:dic forKey:userid];
    }
    
    return userInfoDic;
}

-(NSDictionary *)getPersonInfoByOne:(NSString *)userid
{
    NSDictionary * userInfoDic = nil;
    
    NSString *query = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE userid in(%@)",PersonalDataList,userid];
    FMResultSet *rs = [_dataBase executeQuery:query];
    
    while ([rs next])
    {
        NSString * userInfo = [rs stringForColumn:keyPersonalInfo];
        
        NSData *temp = [NSData dataFromBase64String:userInfo];
        
        userInfoDic=[[CJSONDeserializer deserializer] deserializeAsDictionary:temp error:nil];
    }
    return userInfoDic;
}

#pragma mark - 用户基本信息的存取

-(void)initUserBaseDataDB
{
    if(![_dataBase goodConnection])
        [_dataBase open];
    
    if(![_dataBase tableExists:UserBaseDataList])
    {
        NSDictionary *queryDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                  DBFieldType_TEXT,         KeyDataKey,
                                  DBFieldType_TEXT,         KeyDetailData,
                                  nil];
        NSString *query = [NSString stringWithFormat:@"CREATE TABLE %@ (%@ , PRIMARY KEY(datakey ASC))",UserBaseDataList,[self getPar1StrFromDic:queryDic]];
        
        BOOL ff = [_dataBase executeUpdate:query];
        if(!ff)
        {
            NSLog(@"初始化用户基本信息表失败%@",[[_dataBase lastError] description]);
        }
    }
}
-(void)deleteUserBaseDataWithKey:(NSString *)_key
{
    NSString *query = [NSString stringWithFormat:@"DELETE FROM %@ WHERE datakey = '%@'",UserBaseDataList,_key];
    BOOL s = [_dataBase executeUpdate:query];
    if(!s)
    {
        NSLog(@"deletePersonalDataWithUsers UserBaseDataList资料表 action error:%@",[[_dataBase lastError] description]);
    }
}
-(void)modifyUserBaseDataWithKey:(NSString *)_key andData:(NSDictionary *)dataDic
{
    [self initUserBaseDataDB];
    [self deleteUserBaseDataWithKey:_key];
    NSString *userSaveData = [[CJSONSerializer serializer] serializeDictionary:dataDic];
    userSaveData = [[userSaveData dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
    
    NSMutableString *query = [NSMutableString stringWithFormat:@"INSERT INTO %@ (datakey,detaildata) VALUES('%@','%@')",UserBaseDataList,_key,userSaveData];
    
    BOOL s1 = [_dataBase executeUpdate:query];
    if(!s1)
    {
        NSLog(@"writeUserBaseData database action error:%@",[[_dataBase lastError] description]);
    }
    
}
- (NSDictionary *)getUserBaseDataWithKey:(NSString *)_key
{
    if(MyAppDataManager.useruid.length)
    {
        NSString *query = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE datakey = '%@'",UserBaseDataList,_key];
        FMResultSet *rs = [_dataBase executeQuery:query];
        NSDictionary *amsg = nil;
        while ([rs next]) {
            amsg = [NSDictionary dictionaryWithObjectsAndKeys:
                    [rs stringForColumn:KeyDataKey],    KeyDataKey,
                    [rs stringForColumn:KeyDetailData], KeyDetailData,nil];
            
        }
        NSData *temp = [NSData dataFromBase64String:[amsg valueForKey:KeyDetailData]];
        
        NSDictionary *detailData=[[NSDictionary alloc]initWithDictionary:[[CJSONDeserializer deserializer] deserializeAsDictionary:temp error:nil]];
        
        return [detailData autorelease];
    }
    return [NSDictionary dictionary];
}
-(void)cleanUserOldBaseData
{
    if(MyAppDataManager.useruid.length)
    {
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:[MyAppDataManager getUserBaseDataWithKey:KeyLastSeeDynamicTime]];
            NSLog(@"%@",dic);
            NSArray *enu = [dic allKeys];

            for(NSString *key in enu)
            {
                [self getTheSecondLastOnlineTime:[dic valueForKey:key]];
                
                if([self getTheSecondLastOnlineTime:[dic valueForKey:key]]>7*24*60*60)
                {
                    NSLog(@"删除key : %f %@",[self getTheSecondLastOnlineTime:[dic valueForKey:key]],key);
                    [dic removeObjectForKey:key];
                }
            }
            [self modifyUserBaseDataWithKey:KeyLastSeeDynamicTime andData:dic];
//        });
    }

}

#pragma mark - 清理缓存
//conditionDic存放清理条件：超过一定时间、或其他
-(void)clearPersonDB:(NSDictionary *)conditionDic
{
    if (![_dataBase goodConnection])
    {
        [_dataBase open];
    }
}


#pragma mark - 获取缓存图片

- (UIImage *)imageForImageUrlStr:(NSString *)fileUrlStr
{
    NSString *filePath = [AppComManager pathForMedia:fileUrlStr];
    NSData *imageData = [NSData dataWithContentsOfFile:filePath];
    
    if(imageData)
        return [UIImage imageWithData:imageData];
    else
        return [UIImage imageNamed:@"defaultuser.png"];
}

//获取发送图片、图片、声音时的缓存文件路径
- (UIImage *)msgImageForImageUrlStr:(NSString *)fileUrlStr
{
    NSString *filePath = [AppComManager pathForMsgMedia:fileUrlStr];
    
    NSData *imageData = [NSData dataWithContentsOfFile:filePath];
    if(imageData)
        return [UIImage imageWithData:imageData];
    else
        return [UIImage imageNamed:@"defaultuser.png"];
}

-(NSData *)msgimageDataForImageUrlStr:(NSString *)fileUrlStr
{
    NSString *filePath = [AppComManager pathForMsgMedia:fileUrlStr];
    
    NSData *imageData = [NSData dataWithContentsOfFile:filePath];
    
    return imageData;
}

-(NSData *)imageDataForImageUrlStr:(NSString *)fileUrlStr
{
    NSString *filePath = [AppComManager pathForMedia:fileUrlStr];
    
    NSData *imageData = [NSData dataWithContentsOfFile:filePath];

    return imageData;
}

-(NSData *)imageDataForImageUrlStr:(NSString *)fileUrlStr withFolder:(NSString *)folerName
{
    NSString *filePath = [AppComManager pathForMsgMedia:fileUrlStr cacheFolder:folerName];
    
    NSData *imageData = [NSData dataWithContentsOfFile:filePath];
    
    return imageData;
}

-(NSData *)imageDataForImagePathStr:(NSString *)imagePath
{
    NSData *imageData = [NSData dataWithContentsOfFile:imagePath];
    
    return imageData;
}

//{a j,b k,c l,}   like this
-(NSString *)getPar1StrFromDic:(NSDictionary *)parDic
{
    NSMutableString *str = [NSMutableString stringWithCapacity:1];
    for(NSString *key in parDic)
        [str appendFormat:@"%@ %@,",key,[parDic valueForKey:key]];
    [str deleteCharactersInRange:NSMakeRange(str.length-1, 1)];
    return str;
}

#pragma mark -
//判断好友关系，YES：好友；NO：非好友
-(BOOL)judgeRelationship:(NSString *)userid
{
    NSString *friendIDList = [[[NSMutableDictionary dictionaryWithDictionary:[UserDefaults valueForKey:MyAppDataManager.useruid]] valueForKey:FriendShip] valueForKey:@"h"];
    friendIDList = [NSString stringWithFormat:@",%@,",friendIDList];
    if ([friendIDList rangeOfString:[NSString stringWithFormat:@",%@,",userid]].location != NSNotFound)
    {
        return YES;
    }
    
    return NO;
}

-(NSDate *)getLastShowTime:(NSString *)userid
{
    NSString * tableName = [self getTableNameForUid:userid];
    NSString * selectShowTime =[NSString stringWithFormat: @"SELECT stime FROM %@ WHERE showtime = 1 AND userid = %@  ORDER BY stime DESC LIMIT 0,1",tableName,userid];
    
    FMResultSet * rs = [_dataBase executeQuery:selectShowTime];
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    while ([rs next])
    {
        NSString * stime = [rs stringForColumn:KeyStime];
        NSDate * date = [formatter dateFromString:stime];
        [formatter release];
        return date;
    }
    
    self.lastShowwingTime = [formatter dateFromString:@"1900-01-01 00:00:00"];
    
    [formatter release];
    return self.lastShowwingTime;
}

//检查某用户是否在黑名单中
-(BOOL)checkBlackList:(NSString *)userid
{
    NSString * blackUserIDList = [NSString stringWithFormat:@",%@,",[[[UserDefaults valueForKey:MyAppDataManager.useruid] valueForKey:@"friendlist"] valueForKey:@"x"]];
    
    userid = [NSString stringWithFormat:@",%@,",userid];
    
    if ([blackUserIDList rangeOfString:userid].location != NSNotFound)
    {
        return NO;
    }
    return YES;
}

//查看该消息有没有个人资料，没有个人资料返回NO
-(BOOL)checkUserInfo:(NSDictionary *)dataDic
{
    //查看dataDic中是否有个人资料,有就返回YES
    if ([dataDic valueForKey:keyPersonalInfo])
    {
        return YES;
    }
    
    //查看数据库中是否有个人资料，dataDic中没有个人资料
    NSString * query = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE userid = %@",PersonalDataList,[dataDic valueForKey:KeyFromUid]];
    NSString * userInfo = nil;
    FMResultSet * rs =[_dataBase executeQuery:query];
    while ([rs next])
    {
        userInfo = [rs stringForColumn:keyPersonalInfo];
    }
    
    if (userInfo)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

#pragma 设置信息的高度、主要是图片信息
//设置信息的高度、主要是图片信息
-(double)setHeight:(NSData *)imageData
{
    UIImage * image = [UIImage imageWithData:imageData];
    
    if (image)
    {
        double bl = image.size.width/image.size.height;
        
        if (bl<0.9)//图片比较高，固定宽度：80
        {
            return 90/bl;
        }
        else if (bl >= 0.9 && bl <= 1.1)//图片是正方形的，固定宽度：80
        {
            return 90;
        }
        else//图片比较长，固定长度，290，这是发送闪光字
        {
            if (image.size.width>MaxGIFWith)
            {
                return MaxGIFWith/bl>50?MaxGIFWith/bl:50;
            }
            return image.size.height+5;
        }
    }
    return 90;
}

//设置图片的高度
-(double)setReceiveImageHeight:(NSDictionary *)resDic
{
    if (![_dataBase goodConnection])
    {
        [_dataBase open];
    }
    
    NSString *tableName = [self getTableNameForUid:[resDic valueForKey:@"touid"]];
    
    NSString * selectShowTime = [NSString stringWithFormat:@"SELECT showtime,msgfrom FROM %@ WHERE chatid=?",tableName];
    
    FMResultSet * rs = [_dataBase executeQuery:selectShowTime,[resDic valueForKey:KeyChatid]];
    
    BOOL showtime = NO;
    NSString * msgFrom = nil;
    
    while ([rs next])
    {
        showtime = [rs boolForColumn:KeyShowtime];
        msgFrom = [rs stringForColumn:KeyShowFrom];
    }
    
    NSString *dialogsOneQuery = [NSString stringWithFormat:@"UPDATE %@ SET height=? WHERE chatid=?",tableName];
    
    NSData * data = UIImageJPEGRepresentation([MyAppDataManager msgImageForImageUrlStr:[resDic valueForKey:@"mediaUrlStr"]], 1);
    
    double height = [self setHeight:data];
    
    height += 2*CellMarge + (showtime?TimeLabelHeight:0);
    
    BOOL showFrom=!!([msgFrom isEqual:@"mo"]||([msgFrom isEqual:@"collect"]));
    
    height=height+(showFrom?26:0);
    
    BOOL s1 = [_dataBase executeUpdate:dialogsOneQuery,
               [NSNumber numberWithInteger:height],
               [resDic valueForKey:KeyChatid]
               ];
    if(!s1)
    {
        NSLog(@"setReceiveImageHeight 更新一条聊天记录的状态失败database action error:%@",[[_dataBase lastError] description]);
    }
    else
    {
        return height;
    }
    
    return height;
}

//保存转发的用户的消息，转发给最近对话
-(NSDictionary *)saveTransmitMsg:(NSDictionary *)msgDic andUserIDList:(NSDictionary *)userIDDic
{
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setLocale:[NSLocale currentLocale]];
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *stime = [formatter stringFromDate:[NSDate date]];
    
    //存放用户id和用户对应的chatID
    NSMutableDictionary * useridAndChatIDDic = [NSMutableDictionary dictionaryWithCapacity:20];
    
    //消息包装好的字典
    NSMutableDictionary * amsg = [NSMutableDictionary dictionaryWithDictionary:msgDic];
    
    //更新发送时间
    [amsg setValue:stime forKey:KeyStime];
    [amsg setValue:[NSNumber numberWithBool:YES] forKey:KeyMe];
    
    for (NSString * userid in userIDDic.allKeys)
    {
        //判断msg用不用显示时间
        NSString *chatid = [MyAppDataManager searchMaxChatid:userid];
        
        [amsg setValue:chatid forKey:KeyChatid];
        
        [useridAndChatIDDic setValue:chatid forKey:userid];//将chadid保存下来
        
        //如果现在对话的是原来那条消息的聊天记录则将消息包装后的字典写入现在的对话中
        if ([MyAppDataManager.chatuid isEqualToString:userid])
        {
            //更新数据源，更新界面插入到uitableview 里面去
            
            [MyAppDataManager.dialogs addObject:amsg];
            
            [MyAppDataManager.appChatController.tableView reloadData];
            [MyAppDataManager.appChatController tableViewAutoOffset];
            
            //建立映射关系
            [MyAppDataManager.cellRowMapDic setValue:[NSNumber numberWithInteger:MyAppDataManager.dialogs.count-1] forKey:[amsg valueForKey:KeyChatid]];
        }
        
        [self writeToDetailChatTable:amsg andToUid:userid];
    }
    //保存到对话表
    [self writeToTalkPeopleAll:amsg To:userIDDic.allKeys];
    
    return useridAndChatIDDic;
}

//保存转发的用户的消息，转发给好友
-(NSDictionary *)saveTransmitMsg:(NSDictionary *)msgDic andUseruserInfoDic:(NSDictionary *)userInfoDic
{
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setLocale:[NSLocale currentLocale]];
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *stime = [formatter stringFromDate:[NSDate date]];
    
    //存放用户id和用户对应的chatID
    NSMutableDictionary * useridAndChatIDDic = [NSMutableDictionary dictionaryWithCapacity:20];
    
    //消息包装好的字典
    NSMutableDictionary * amsg = [NSMutableDictionary dictionaryWithDictionary:msgDic];
    
    //更新发送时间
    [amsg setValue:stime forKey:KeyStime];
    [amsg setValue:[NSNumber numberWithBool:YES] forKey:KeyMe];
    
    for (NSString * userid in userInfoDic.allKeys)
    {
        //判断msg用不用显示时间
        NSString *chatid = [MyAppDataManager searchMaxChatid:userid];
        
        [amsg setValue:chatid forKey:KeyChatid];
        
        [useridAndChatIDDic setValue:chatid forKey:userid];//将chadid保存下来
        
        //如果现在对话的是原来那条消息的聊天记录则将消息包装后的字典写入现在的对话中
        if ([MyAppDataManager.chatuid isEqualToString:userid])
        {
            //更新数据源，更新界面插入到uitableview 里面去
            
            [MyAppDataManager.dialogs addObject:amsg];
            [MyAppDataManager.appChatController.tableView reloadData];
            [MyAppDataManager.appChatController tableViewAutoOffset];
            
            //建立映射关系
            [MyAppDataManager.cellRowMapDic setValue:[NSNumber numberWithInteger:MyAppDataManager.dialogs.count-1] forKey:[amsg valueForKey:KeyChatid]];
        }
        
        [self writeToDetailChatTable:amsg andToUid:userid];
    }
    //保存到对话表
    [self writeToTalkPeopleAll:amsg ToUserinfor:userInfoDic];
    
    return useridAndChatIDDic;
}

-(void)showTime:(NSString *)str
{
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setLocale:[NSLocale currentLocale]];
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
    NSString *stime = [formatter stringFromDate:[NSDate date]];
    NSLog(@"%@:%@",str,stime);
}
@end